//
//  YWInspectionMissionManager.m
//  maintain
//
//  Created by Kyo on 16/5/25.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWInspectionMissionManager.h"
#import "YWDBTool.h"
#import "YWInspectionMissionDBManager.h"
#import "WMHttpTool.h"
#import "YWCommonTool.h"
#import "MJExtension.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "NSDate+Additions.h"
#import "YWLoginTool.h"
#import "YWLoginUser.h"

#import "YWInspectionMissionModel.h"
#import "YWInspectionLineRecord.h"
#import "YWInspectionEquipmentRecord.h"
#import "YWResourceManager.h"
#import "YWInspectionEquipmentRecord.h"
#import "YWEquipment.h"
#import "YWEquipmentFieldRecord.h"
#import "YWBuildingManager.h"
#import "YWKeepWatchMissionManager.h"
#import "YWMissionManager.h"
#import "YWReportTroubleModel.h"
#import "YWBuilding.h"
#import "YWEquipmentType.h"
#import "YWEquipmentManager.h"
#import "YWCirculationManager.h"
#import "YWNotifyManager.h"
#import <Bugly/Bugly.h>
#import "YWScanEquipmentNotMatchVC.h"
//#import "YWDoEquipmentInspectionTableViewController.h"
#import "YWDoEquipmentMissionTableViewController.h"
#import "YWDoLocationInspectionTableViewController.h"
#import "YWLogRecordTool.h"
#import "YWReplyDBManager.h"
#import "YWReply.h"
#import "YWReportTroubleModel.h"
#import "YWEwinManager.h"

static BOOL isUploading = NO;

@interface YWInspectionMissionManager ()
@property (nonatomic, strong) dispatch_group_t group;
//@property (nonatomic, strong) dispatch_queue_t serialQueue;
//@property (nonatomic, strong) dispatch_semaphore_t signal;
@end

@implementation YWInspectionMissionManager
YWSingletonM(Manager)

- (dispatch_group_t)group{
    if (!_group) {
        _group = dispatch_group_create();
    }
    return _group;
}

//- (dispatch_queue_t)serialQueue{
//    if (!_serialQueue) {
//        _serialQueue = dispatch_queue_create("uploadPatrolRecordserialQueue", DISPATCH_QUEUE_SERIAL); //创建上传串行队列
//    }
//    return _serialQueue;
//}
//
//- (dispatch_semaphore_t)signal{
//    if (!_signal) {
//        _signal = dispatch_semaphore_create(1);
//    }
//    return _signal;
//}

- (BOOL)saveInspectionMissionWithArray:(NSArray*)inspectionMission{
    return [[YWInspectionMissionDBManager shareManager] saveInspectionMissionWithArray:inspectionMission];
}

- (NSString *)allInspectionMissionIds{
    return [[YWInspectionMissionDBManager shareManager] allInspectionMissionIds];
}

- (BOOL)updateInspectionMissionDeleteStatusWithMissionId:(NSInteger)inspectionMissionId{
    return [[YWInspectionMissionDBManager shareManager] updateInspectionMissionDeleteStatusWithMissionId:inspectionMissionId];
}

- (NSArray *)allInspectionMissions{
    return [[YWInspectionMissionDBManager shareManager] allInspectionMissions];
}

- (NSArray *)inspectionMissionsWithPage:(NSInteger)page{
    return [[YWInspectionMissionDBManager shareManager] inspectionMissionsWithPage:page];
}

- (NSArray *)allInspectionLines{
    return [[YWInspectionMissionDBManager shareManager] allInspectionLines];
}

- (NSArray *)twoTypeInspectionMissions{
    NSArray *missions = [[YWInspectionMissionDBManager shareManager] myInspectionMissions];
    __block NSMutableArray* matchEquipmentMissions = [NSMutableArray array];
    __block NSMutableArray* matchLocationMissions = [NSMutableArray array];
    [missions enumerateObjectsUsingBlock:^(YWInspectionMissionModel*  _Nonnull inspectionMission, NSUInteger idx, BOOL * _Nonnull stop) {
        if (inspectionMission.inspectionLine.lineType == YWInspectionLineTypeEquipment) {
            [matchEquipmentMissions addObject:inspectionMission];
        }else if (inspectionMission.inspectionLine.lineType == YWInspectionLineTypeLocation){
            [matchLocationMissions addObject:inspectionMission];
        }
    }];
    return @[matchLocationMissions,matchEquipmentMissions];
}

- (YWInspectionMissionModel *)inspectionMissionWithMissionId:(NSInteger)missionId{
    return [[YWInspectionMissionDBManager shareManager] inspectionMissionWithMissionId:missionId];
}

- (BOOL)updateInspectionLineRecordWithArray:(NSArray*)inspectionLineRecords{
    return [[YWInspectionMissionDBManager shareManager] updateInspectionLineRecordWithArray:inspectionLineRecords];
}

- (BOOL)updateInspectionLineRecordWithNewWorkData:(NSArray*)inspectionLineRecords{
    return [[YWInspectionMissionDBManager shareManager] updateInspectionLineRecordWithNewWorkData:inspectionLineRecords];
}

- (BOOL)updateInspectionEquipmentRecordWithArray:(NSArray*)inspectionEquipmentRecords{
    return [[YWInspectionMissionDBManager shareManager] updateInspectionEquipmentRecordWithArray:inspectionEquipmentRecords];
}

- (BOOL)updateLocationInspectionRecordWithArray:(NSArray *)locationInspectionRecords{
    return [[YWInspectionMissionDBManager shareManager] updateLocationInspectionRecordWithArray:locationInspectionRecords];
}

- (BOOL)updateInspectionEquipmentRecordUploadStatus:(YWInspectionEquipmentRecordUploadStatus)uploadStatus inspectionEquipmentRecordId:(NSString*)recordId{
    return [[YWInspectionMissionDBManager shareManager] updateInspectionEquipmentRecordUploadStatus:uploadStatus inspectionEquipmentRecordId:recordId];
}

- (NSArray*)inspectionEquipmentRecordsWithUploadStatusFailWithType:(YWInspectionEquipmentRecordType)type{
    return [[YWInspectionMissionDBManager shareManager] inspectionEquipmentRecordsWithUploadStatusFailWithType:type];
}

- (NSArray *)uploadFailedInspectionRecords{
    return [[YWInspectionMissionDBManager shareManager] uploadFailedInspectionRecords];
}

- (YWInspectionLineRecord *)latestInspectionLineRecordUniqueTag:(NSString *)uniqueTag{
    return [self inspectionLineRecordWithUniqueTag:uniqueTag];
}

- (YWInspectionLineRecord*)inspectionLineRecordWithUniqueTag:(NSString*)uniqueTag{
    return [[YWInspectionMissionDBManager shareManager] inspectionLineRecordWithUniqueTag:uniqueTag];
}

- (YWInspectionLineModel *)inspectionLineWithLineId:(NSInteger)inspectionLineId{
    return [[YWInspectionMissionDBManager shareManager] inspectionLineWithLineId:inspectionLineId];
}

- (NSArray*)inspectionLineRecordWithInspectionMission:(YWInspectionMissionModel*)inspectionMission page:(NSInteger)page{
    return [[YWInspectionMissionDBManager shareManager] inspectionLineRecordWithInspectionMission:inspectionMission page:page];
}

- (NSArray*)inspectionLineRecordWithPage:(NSInteger)page{
    return [[YWInspectionMissionDBManager shareManager] inspectionLineRecordWithPage:page];
}

-(BOOL)updateReadStatusWithInspectionMissionId:(NSInteger)inspectionMissionId{
    return [[YWInspectionMissionDBManager shareManager] updateReadStatusWithInspectionMissionId:inspectionMissionId];
}

- (NSArray*)inspectionEquipmentRecordWithUniqueTag:(NSString*)uniqueTag{
    return [[YWInspectionMissionDBManager shareManager] inspectionEquipmentRecordWithUniqueTag:uniqueTag];
}

- (NSInteger)countOfInspectionEquipmentRecordWithUniqueTag:(NSString*)uniqueTag{
    return [[YWInspectionMissionDBManager shareManager] countOfInspectionEquipmentRecordWithUniqueTag:uniqueTag];
}

- (NSArray *)allInspectionEquipmentWithLineId:(NSInteger)inspectionLineId{
    return [[YWInspectionMissionDBManager shareManager] allInspectionEquipmentWithLineId:inspectionLineId];
}

- (NSArray*)allInspectionLocationWithInspectionLineId:(NSInteger)inspectionLineId{
    return [[YWInspectionMissionDBManager shareManager] allInspectionLocationWithInspectionLineId:inspectionLineId];
}

- (NSArray*)inspectionLocationNoteWithLocationId:(NSInteger)locationId lineIds:(NSArray*)inspectionLineIdArray{
    return [[YWInspectionMissionDBManager shareManager] inspectionLocationNoteWithLocationId:locationId lineIds:inspectionLineIdArray];
}

- (NSArray*)allInspectionEquipmentWithLineId:(NSInteger)inspectionLineId qrcodeId:(NSString*)qrcodeId orLocationId:(NSInteger)locationId{
    return [[YWInspectionMissionDBManager shareManager] allInspectionEquipmentWithLineId:inspectionLineId qrcodeId:qrcodeId orLocationId:locationId];
}

- (NSArray*)allInspectionEquipmentWithLineId:(NSInteger)inspectionLineId qrcodeId:(NSString*)qrcodeId equipmentTypeId:(NSInteger)equipmentTypeId{
    return [[YWInspectionMissionDBManager shareManager] allInspectionEquipmentWithLineId:inspectionLineId qrcodeId:qrcodeId equipmentTypeId:equipmentTypeId];
}

- (NSArray*)inspectionLineDataWithInspectionLine:(YWInspectionLineModel*)inspectionLine{
    if (inspectionLine.lineType == YWInspectionLineTypeEquipment) {
        NSMutableArray *dataArray = [NSMutableArray array];
        NSArray *allEquipments = [self allInspectionEquipmentWithLineId:inspectionLine.inspectionLineId];
        NSString *locationName = nil;
        for (YWEquipment *equipment in allEquipments) {
            locationName = [[YWBuildingManager shareManager]equipmentLocation:equipment];
            NSString *content = equipment.equipmentName?:NSLocalizedString(@"unknowEquipment", nil);
            //NSString *timeStr = @"【未巡】";
            [dataArray addObject:@{YWMissionManagerDicLocation:locationName,YWMissionManagerDicStatusType:@(YWInspectionEquipmentStatusTypeUnfinish),YWMissionManagerDicContent:content}];
        }
        return dataArray;
    }else{
        NSMutableArray *dataArray = [NSMutableArray array];
        NSArray *allLocations = [self allInspectionLocationWithInspectionLineId:inspectionLine.inspectionLineId];
        NSString *locationName = nil;
        for (YWInspectionLineLocationRel *lineLocation in allLocations) {
            locationName = [[YWBuildingManager shareManager]areaLocationWithLocationId:lineLocation.locationId];
            //NSString *timeStr = @"【未巡】";
            [dataArray addObject:@{YWMissionManagerDicLocation:locationName,YWMissionManagerDicStatusType:@(YWInspectionEquipmentStatusTypeUnfinish)}];
        }
        return dataArray;
    }
}

//巡查设备
- (NSArray *)timeLineViewDataArryWithEquipmentRecord:(YWInspectionLineRecord*)record{
    NSMutableArray *dataArray = [NSMutableArray array];
    NSArray *finishEquipmentRecords = [self inspectionEquipmentRecordWithUniqueTag:record.uniqueTag];
    NSArray *allEquipments = nil;
    if (record.inspectionLineId == 0) {
        NSMutableArray *equipments = [NSMutableArray array];
        for (YWInspectionEquipmentRecord* equipmentRecord in finishEquipmentRecords) {
            YWEquipment *equipment = equipmentRecord.equipment;
            if (equipment) {
                [equipments addObject:equipment];
            }
        }
        allEquipments = [[NSArray alloc] initWithArray:equipments];
    }else{
        allEquipments = [self allInspectionEquipmentWithLineId:record.inspectionLineId];
    }
    NSString *timeStr = nil;
    NSString *locationName = nil;
    NSString *content = nil;
    for (YWEquipment *equipment in allEquipments) {
        BOOL isFinish = NO;
        if (finishEquipmentRecords.count>0) {
            NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K == %@", @"equipmentId", equipment.equipmentId];
            NSArray *array = [finishEquipmentRecords filteredArrayUsingPredicate:searchPredicate];
            if (array.count>0) {
                isFinish = YES;
                YWInspectionEquipmentRecord* equipmentRecord = array[0];
                timeStr = [YWCommonTool showTime:equipmentRecord.executeTime/1000 andFormatter:KTimeFormatShortTimeDate];
                if (equipmentRecord.executor.userName.length) {
                    timeStr = [NSString stringWithFormat:@"%@ %@",equipmentRecord.executor.userName,timeStr];
                }
                locationName = [[YWBuildingManager shareManager]equipmentLocationNobuilding:equipment];
                content = equipment.equipmentName?:@"";
                [dataArray addObject:@{YWMissionManagerDicLocation:locationName,YWMissionManagerDicStatusType:@(equipmentRecord.status == YWInspectionEquipmentRecordStatusNormal ? YWInspectionEquipmentStatusTypeFinishNormal:YWInspectionEquipmentStatusTypeFinishTrouble),YWMissionManagerDicContent:content,YWMissionManagerDicTime:timeStr,YWMissionManagerDicRecordObj:equipmentRecord?:@""}];
            }
        }
        if (!isFinish) {
            locationName = [[YWBuildingManager shareManager]equipmentLocationNobuilding:equipment];
            content = equipment.equipmentName?:NSLocalizedString(@"unknowEquipment", nil);
            timeStr = @"【未巡】";
            [dataArray addObject:@{YWMissionManagerDicLocation:locationName,YWMissionManagerDicStatusType:@(YWInspectionEquipmentStatusTypeUnfinish),YWMissionManagerDicContent:content,YWMissionManagerDicTime:timeStr}];
        }
    }
    return dataArray;
    
}

- (NSArray*)timeLineViewDataWithInspectionMission:(YWInspectionMissionModel*)inspectionMission orLineRecord:(YWInspectionLineRecord*)inspectionLineRecord
{
    NSString *uniqueTag = inspectionLineRecord ? inspectionLineRecord.uniqueTag : [YWCommonTool uniqueTagWithMission:inspectionMission];
    YWInspectionLineRecord *record = [self latestInspectionLineRecordUniqueTag:uniqueTag];
    if (record) {
        return [self timeLineViewDataArryWithEquipmentRecord:record];
    }else{
        return [self allEquipmentUnfinishWithInspectionLineId:inspectionMission.inspectionLine.inspectionLineId];
    }
}
- (NSArray*)timeLineViewDataWithInspectionRecord:(YWInspectionLineRecord *)record
{
    if (record) {
        return [self timeLineViewDataArryWithEquipmentRecord:record];
    }else{
        return [self allEquipmentUnfinishWithInspectionLineId:record.inspectionLineId];
    }
}

//巡查位置
- (NSArray *)timeLineViewDataArryWithLocationRecord:(YWInspectionLineRecord*)record{
    NSMutableArray *dataArray = [NSMutableArray array];
    NSArray *finishLocationRecords = [self inspectionEquipmentRecordWithUniqueTag:record.uniqueTag];
    NSArray *allLocations = [self allInspectionLocationWithInspectionLineId:record.inspectionLineId];
    if (allLocations.count==0 && finishLocationRecords.count>0) {
        NSMutableArray *locationsArray = [NSMutableArray array];
        for (YWInspectionEquipmentRecord* record in finishLocationRecords) {
            YWInspectionLineLocationRel *locationRel = [[YWInspectionLineLocationRel alloc]init];
            locationRel.locationId = record.locationId;
            [locationsArray addObject:locationRel];
        }
        allLocations = [[NSArray alloc]initWithArray:locationsArray];
    }
    NSString *timeStr = nil;
    NSString *locationName = nil;
    for (YWInspectionLineLocationRel *locationRel in allLocations) {
        BOOL isFinish = NO;
        if (finishLocationRecords.count>0) {
            NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"locationId", locationRel.locationId];
            NSArray *array = [finishLocationRecords filteredArrayUsingPredicate:searchPredicate];
            if (array.count>0) {
                isFinish = YES;
                YWInspectionEquipmentRecord* equipmentRecord = array[0];
                timeStr = [YWCommonTool showTime:equipmentRecord.executeTime/1000 andFormatter:KTimeFormatShortTimeDate];
                if (equipmentRecord.executor.userName.length) {
                    timeStr = [NSString stringWithFormat:@"%@ %@",equipmentRecord.executor.userName,timeStr];
                }
                locationName = [[YWBuildingManager shareManager]areaLocationNobuildingWithId:locationRel.locationId];
                //                        NSString *content = locationName;
                [dataArray addObject:@{YWMissionManagerDicLocation:locationName,YWMissionManagerDicStatusType:@(equipmentRecord.status == YWInspectionEquipmentRecordStatusNormal ? YWInspectionEquipmentStatusTypeFinishNormal:YWInspectionEquipmentStatusTypeFinishTrouble),YWMissionManagerDicTime:timeStr,YWMissionManagerDicRecordObj:equipmentRecord?:@""}];
            }
        }
        if (!isFinish) {
            locationName = [[YWBuildingManager shareManager]areaLocationNobuildingWithId:locationRel.locationId];
            timeStr = @"【未巡】";
            [dataArray addObject:@{YWMissionManagerDicLocation:locationName,YWMissionManagerDicStatusType:@(YWInspectionEquipmentStatusTypeUnfinish),YWMissionManagerDicTime:timeStr}];
        }
    }
    return dataArray;
}

- (NSArray*)timeLineViewDataWithLocationMission:(YWInspectionMissionModel*)inspectionMission orLineRecord:(YWInspectionLineRecord*)inspectionLineRecord
{
    NSString *uniqueTag = inspectionLineRecord ? inspectionLineRecord.uniqueTag : [YWCommonTool uniqueTagWithMission:inspectionMission];
    YWInspectionLineRecord *record = [self latestInspectionLineRecordUniqueTag:uniqueTag];
    if (record) {
        return [self timeLineViewDataArryWithLocationRecord:record];
    }else{
        return [self allLocationUnfinishWithInspectionLineId:inspectionMission.inspectionLine.inspectionLineId];
    }
}
- (NSArray*)timeLineViewDataWithLocationRecord:(YWInspectionLineRecord *)record
{
    if (record) {
        return [self timeLineViewDataArryWithLocationRecord:record];
    }else{
        return [self allLocationUnfinishWithInspectionLineId:record.inspectionLineId];
    }
}
-(NSArray*)allEquipmentUnfinishWithInspectionLineId:(NSInteger)inspectionLineId
{
    NSMutableArray *dataArray = [NSMutableArray array];
    NSArray *allEquipments = [self allInspectionEquipmentWithLineId:inspectionLineId];
    NSString *locationName = nil;
    for (YWEquipment *equipment in allEquipments) {
        locationName = [[YWBuildingManager shareManager]equipmentLocationNobuilding:equipment];
        NSString *content = equipment.equipmentName?:NSLocalizedString(@"unknowEquipment", nil);
        NSString *timeStr = @"【未巡】";
        [dataArray addObject:@{YWMissionManagerDicLocation:locationName,YWMissionManagerDicStatusType:@(YWInspectionEquipmentStatusTypeUnfinish),YWMissionManagerDicContent:content,YWMissionManagerDicTime:timeStr}];
    }
    return dataArray;
}
-(NSArray*)allLocationUnfinishWithInspectionLineId:(NSInteger)inspectionLineId
{
    NSMutableArray *dataArray = [NSMutableArray array];
    NSArray *allLocations = [self allInspectionLocationWithInspectionLineId:inspectionLineId];
    NSString *locationName = nil;
    for (YWInspectionLineLocationRel *lineLocation in allLocations) {
        locationName = [[YWBuildingManager shareManager]areaLocationNobuildingWithId:lineLocation.locationId];
        NSString *timeStr = @"【未巡】";
        [dataArray addObject:@{YWMissionManagerDicLocation:locationName,YWMissionManagerDicStatusType:@(YWInspectionEquipmentStatusTypeUnfinish),YWMissionManagerDicTime:timeStr}];
    }
    return dataArray;
}

- (YWInspectionJudgeType)judgeTypeWithMission:(YWInspectionMissionModel*)inspectionMission{
    //任务状态
    YWInspectionJudgeType type = YWInspectionJudgeTypeMatch;
    if (inspectionMission.status==-1) {
        //[YWCommonTool showTextHUDWithContent:@"任务已撤回"];
        return YWInspectionJudgeTypeMissionHasCancel;
    }
    //任务的巡更星期
    BOOL istotay = NO;
    for (YWInspectionLineWeekRel* weekRel in inspectionMission.inspectionLine.weekRels) {
        NSInteger weekDay = [NSDate date].weekday;
        //周日是1，周一是2，周六是7
        if (weekRel.week == weekDay - 1) {
            istotay = YES;
            break;
        }
    }
    if (!istotay) {
        //[YWCommonTool showTextHUDWithContent:@"今天不是巡查日"];
        return YWInspectionJudgeTypeNotWeekDay;
    }
    //间隔时间是0的数据错误问题
    if (inspectionMission.inspectionLine.intervalMinute<=0) {
        return YWInspectionJudgeTypeOutOfMissionTime;
    }
    //是否在工作时间内
    NSTimeInterval currentIntrval = [[NSDate date] timeIntervalSince1970]*1000;
    NSDate *currentDate = [NSDate dateWithTimeIntervalSince1970:currentIntrval/1000];
    NSDate *missionStartDate = [NSDate dateWithTimeIntervalSince1970:inspectionMission.startDate/1000];
    NSDate *missionEndDate = [NSDate dateWithTimeIntervalSince1970:inspectionMission.endDate/1000];
    BOOL rightDate = (currentDate.year == missionStartDate.year && currentDate.month== missionStartDate.month && currentDate.day == missionStartDate.day) || (currentDate.year == missionEndDate.year && currentDate.month== missionEndDate.month && currentDate.day == missionEndDate.day);
    if (rightDate) {
        //是任务的日期
    }else{
        if (!(inspectionMission.startDate<=currentIntrval && currentIntrval<=inspectionMission.endDate)) {
            return YWInspectionJudgeTypeOutOfMissionTime;
        }
    }
    
    NSString *todayStr = [YWCommonTool showDate:[[NSDate date] timeIntervalSince1970]];
    NSString *startStr= [NSString stringWithFormat:@"%@ %@:00",todayStr,inspectionMission.startTime];
    NSTimeInterval startInterval = [YWCommonTool timeIntervalWithDatestring:startStr dateFormatter:KTimeFormatFullDateAndTime] *1000;
     
    NSString *endStr= [NSString stringWithFormat:@"%@ %@:00",todayStr,inspectionMission.endTime];
    NSTimeInterval endInterval = [YWCommonTool timeIntervalWithDatestring:endStr dateFormatter:KTimeFormatFullDateAndTime] *1000;
    
    
    if (startInterval > endInterval) {
        //隔夜
        NSString *todayZeroTime = [YWCommonTool showDate:currentIntrval/1000];
//        endStr= [NSString stringWithFormat:@"%@ %@:00",todayZeroTime,inspectionMission.endTime];
//        endInterval = [YWCommonTool timeIntervalWithDatestring:endStr dateFormatter:KTimeFormatFullDateAndTime] *1000;
        
        todayZeroTime = [NSString stringWithFormat:@"%@ 00:00:00",todayZeroTime];
        NSTimeInterval todayZeroTimeInterVal = [YWCommonTool timeIntervalWithDatestring:todayZeroTime dateFormatter:KTimeFormatFullDateAndTime]*1000;
        
        NSString *tomorrowZeroTime = [YWCommonTool showDate:[[NSDate dateTomorrow]timeIntervalSince1970]];
        tomorrowZeroTime = [NSString stringWithFormat:@"%@ 00:00:00",tomorrowZeroTime];
        NSTimeInterval tomorrowZeroTimeInterVal = [YWCommonTool timeIntervalWithDatestring:tomorrowZeroTime dateFormatter:KTimeFormatFullDateAndTime]*1000;
        
        
        NSDate *missionStartDate = [NSDate dateWithTimeIntervalSince1970:inspectionMission.startDate/1000];
        //判断今天是不是任务的开始日期
        if (missionStartDate.year == [NSDate date].year && missionStartDate.month == [NSDate date].month && missionStartDate.day == [NSDate date].day) {
            if ((currentIntrval >= startInterval && currentIntrval <=tomorrowZeroTimeInterVal)) {
                return type;
            }else{
                return YWInspectionJudgeTypeOutOfMissionTime;
            }
        }else{
            if ((currentIntrval >= startInterval && currentIntrval <=tomorrowZeroTimeInterVal) || (currentIntrval>= todayZeroTimeInterVal && currentIntrval<=endInterval)) {
                return type;
            }else{
                return YWInspectionJudgeTypeOutOfMissionTime;
            }
        }
        
    }else if ([inspectionMission.startTime isEqualToString:@"00:00"] && [inspectionMission.endTime isEqualToString:@"00:00"]){
        return type;
    }
    else{
        //同一天  //不在任务的执行时间内
        if (!(currentIntrval >= startInterval && currentIntrval <= endInterval)) {
            return YWInspectionJudgeTypeOutOfMissionTime;
        }
    }
    return type;
}
- (NSString*)typeNameWithJudgeType:(YWInspectionJudgeType)judgeType{
    NSString *typeName = nil;
    switch (judgeType) {
        case YWInspectionJudgeTypeMissionHasCancel:
            typeName = NSLocalizedString(@"missionHasCancel", nil);//@"任务已撤回";
            break;
        case YWInspectionJudgeTypeNotWeekDay:
            typeName = NSLocalizedString(@"todayIsNotInspectionDay", nil);//@"今天不是巡查日";
            break;
        case YWInspectionJudgeTypeOutOfMissionTime:
            typeName = NSLocalizedString(@"currentTimeIsNotInspectionTime", nil);//@"不在每日巡查时间段内";
            break;
            
        default:
            break;
    }
    return typeName;
}

- (YWInspectionEquipmentQrcodeResult)judgeInspectionWithInspectionEquipment:(NSArray* )inspectionEquipments equipmentRecord:(NSArray*)equipmentRecord qrcodeEquipment:(NSArray*)qrcodeEquipments{
    BOOL isInspectionPoint = NO;//判断是不是巡查点
    for (YWEquipment *qrcodeEqu in qrcodeEquipments) {
//        for (YWEquipment *inspectionEqu in inspectionEquipments) {
//            if ([qrcodeEqu.equipmentId isEqualToString:inspectionEqu.equipmentId]) {
//                isInspectionPoint = YES;
//                break;
//            }
//        }
        NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K == %@", @"equipmentId", qrcodeEqu.equipmentId];
        NSArray *array = [inspectionEquipments filteredArrayUsingPredicate:searchPredicate];
        if (array.count>0) {
            isInspectionPoint = YES;
            break;
        }
    }
    
    if (!isInspectionPoint) {
        return YWInspectionEquipmentQrcodeResultUnMatch;
    }else{
        for (YWEquipment *qrcodeEqu in qrcodeEquipments) {
            BOOL contailEquipment = NO;
//            for (YWInspectionEquipmentRecord *equRecord in equipmentRecord) {
//                if ([equRecord.equipment.equipmentId isEqualToString:qrcodeEqu.equipmentId]) {
//                    contailEquipment = YES;
//                }
//            }
            NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K == %@", @"equipmentId", qrcodeEqu.equipmentId];
            NSArray *array = [equipmentRecord filteredArrayUsingPredicate:searchPredicate];
            if (array.count>0) {
                contailEquipment = YES;
            }
            if (contailEquipment == NO) {
                return YWInspectionEquipmentQrcodeResultNoPatrol;
            }
        }
        return YWInspectionEquipmentQrcodeResultHasPatrol;
    }
}
- (YWInspectionEquipmentQrcodeResult)judgeInspectionPointWithLocation:(NSArray* )inspectionLocation pointRecord:(NSArray*)pointRecord locationId:(NSInteger)locationId{
    BOOL isPatrolPoint = NO;
//    for (YWInspectionLineLocationRel *locationRel in inspectionLocation) {
//        if (locationRel.locationId == locationId) {
//            isPatrolPoint = YES;
//            break;
//        }
//    }
    NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"locationId", locationId];
    NSArray *array = [inspectionLocation filteredArrayUsingPredicate:searchPredicate];
    if (array.count>0) {
        isPatrolPoint = YES;
    }
    if (!isPatrolPoint) {
        return YWInspectionEquipmentQrcodeResultUnMatch;
    }else{
//        for (YWInspectionEquipmentRecord *record in pointRecord) {
//            if (record.locationId == locationId) {
//                return YWInspectionEquipmentQrcodeResultHasPatrol;
//            }
//        }
        NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"locationId", locationId];
        NSArray *array = [pointRecord filteredArrayUsingPredicate:searchPredicate];
        if (array.count>0) {
            return YWInspectionEquipmentQrcodeResultHasPatrol;
        }
        return YWInspectionEquipmentQrcodeResultNoPatrol;
    }
}

- (YWInspectionLineRecord *)createLooperRecordWith:(YWInspectionMissionModel*)inspectionMission uniqueTag:(NSString*)uniqueTag{
    YWInspectionLineRecord *record = [[YWInspectionLineRecord alloc]init];
    record.inspectionLineId = inspectionMission.inspectionLine.inspectionLineId;
    record.uniqueTag = uniqueTag;
    record.count = 0;
    NSTimeInterval nowTime = [[NSDate date] timeIntervalSince1970]*1000;
    record.startTime = nowTime;
    record.endTime = nowTime;
    record.result = YWInspectionLineRecordResultUnfinishAndNormal;
    YWLoginUser *currentUser = [YWLoginTool loginUser];
    record.executorIds = [NSString stringWithFormat:@"%ld",(long)currentUser.uniqueId];
    record.inspectionMissionId = inspectionMission.inspectionMissionId;
    return record;
}

- (void)qrcodeSuccessWithEquipmentInspection:(YWInspectionMissionModel *)inspectionMission qrcodeId:(NSString *)qrcodeId noQrcodeLocationId:(NSInteger)noQrcodeLocationId uniqueTag:(NSString *)uniqueTag wReader:(UIViewController *)wReader isFromLedger:(BOOL)isFromLedger{
    NSInteger locationId = 0;
    if (qrcodeId) {
        locationId = [[YWEquipmentManager shareManager] locationIdWithQrcodeId:qrcodeId];
    }else if (noQrcodeLocationId){
        locationId = noQrcodeLocationId;
    }
    NSArray *equipmentArray = [[YWInspectionMissionManager shareManager] allInspectionEquipmentWithLineId:inspectionMission.inspectionLine.inspectionLineId];
    
    NSArray *pointRecord = [[YWInspectionMissionManager shareManager]inspectionEquipmentRecordWithUniqueTag:uniqueTag];
    
    NSArray *allNeedInspectionEquipment = [[YWInspectionMissionManager shareManager] allInspectionEquipmentWithLineId:inspectionMission.inspectionLine.inspectionLineId qrcodeId:qrcodeId orLocationId:locationId];
    YWInspectionEquipmentQrcodeResult pointJudge = [[YWInspectionMissionManager shareManager]judgeInspectionWithInspectionEquipment:equipmentArray equipmentRecord:pointRecord qrcodeEquipment:allNeedInspectionEquipment];
    if (pointJudge==YWInspectionEquipmentQrcodeResultUnMatch) {
        YWScanEquipmentNotMatchVC* senmVC = [[YWScanEquipmentNotMatchVC alloc] init];
        senmVC.showContent = NSLocalizedString(@"isNotInspectionLocation", nil);//@"该位置不是巡查点";
        [wReader.navigationController pushViewController:senmVC animated:YES];
    }else if (pointJudge==YWInspectionEquipmentQrcodeResultHasPatrol){
        YWScanEquipmentNotMatchVC* senmVC = [[YWScanEquipmentNotMatchVC alloc] init];
        senmVC.showContent = NSLocalizedString(@"currentEquipmentHasBeenInspection", nil);//@"该设备已经巡查了";
        [wReader.navigationController pushViewController:senmVC animated:YES];
    }else{
        YWDoEquipmentMissionTableViewController *doEquipmentInspectVc = [[YWDoEquipmentMissionTableViewController alloc] init];
        doEquipmentInspectVc.qrcodeID = qrcodeId;
        doEquipmentInspectVc.locationId = locationId >0? locationId : noQrcodeLocationId;
        doEquipmentInspectVc.inspectionMission = inspectionMission;
        if (isFromLedger) {
            doEquipmentInspectVc.isFromLedger = YES;
        }
        [wReader.navigationController pushViewController:doEquipmentInspectVc animated:YES];
    }
}

- (void)qrcodeSuccessWithLocationInspection:(YWInspectionMissionModel *)inspectionMission qrcodeId:(NSString *)qrcodeId noQrcodeLocationId:(NSInteger)noQrcodeLocationId uniqueTag:(NSString *)uniqueTag wReader:(UIViewController *)wReader isFromLedger:(BOOL)isFromLedger{
    NSInteger locationId = 0;
    if (qrcodeId) {
        locationId = [[YWEquipmentManager shareManager] locationIdWithQrcodeId:qrcodeId];
    }else if (noQrcodeLocationId){
        locationId = noQrcodeLocationId;
    }
    NSArray *allLocations = [[YWInspectionMissionManager shareManager] allInspectionLocationWithInspectionLineId:inspectionMission.inspectionLine.inspectionLineId];
    
    NSArray *pointRecord = [[YWInspectionMissionManager shareManager]inspectionEquipmentRecordWithUniqueTag:uniqueTag];
    
    YWInspectionEquipmentQrcodeResult pointJudge = [[YWInspectionMissionManager shareManager]judgeInspectionPointWithLocation:allLocations pointRecord:pointRecord locationId:locationId];
    if (pointJudge==YWInspectionEquipmentQrcodeResultUnMatch) {
        YWScanEquipmentNotMatchVC* senmVC = [[YWScanEquipmentNotMatchVC alloc] init];
        senmVC.showContent = NSLocalizedString(@"isNotInspectionLocation", nil);//@"该位置不是巡查点";
        [wReader.navigationController pushViewController:senmVC animated:YES];
    }else if (pointJudge==YWInspectionEquipmentQrcodeResultHasPatrol){
        YWScanEquipmentNotMatchVC* senmVC = [[YWScanEquipmentNotMatchVC alloc] init];
        senmVC.showContent = NSLocalizedString(@"currentLocationHasBeenInspection", nil);//@"该位置已经巡查了";
        [wReader.navigationController pushViewController:senmVC animated:YES];
    }else{
        if (locationId<=0 && noQrcodeLocationId<=0) {
            YWScanEquipmentNotMatchVC* senmVC = [[YWScanEquipmentNotMatchVC alloc] init];
            senmVC.showContent = NSLocalizedString(@"currentInspectionLocationIsError", nil);//@"当前巡查位置错误";
            [wReader.navigationController pushViewController:senmVC animated:YES];
        }else{
            YWDoLocationInspectionTableViewController *doingVC= [[YWDoLocationInspectionTableViewController alloc]init];
            if (isFromLedger) {
                doingVC.isFromLedger = YES;
            }
            doingVC.inspectionMission = inspectionMission;
            doingVC.locationId = locationId >0 ? locationId : noQrcodeLocationId;
            doingVC.qrcodeId = qrcodeId;
            [wReader.navigationController pushViewController:doingVC animated:YES];
        }
    }
}

- (void)requestInspectionLineWithBuildingId:(NSString *)buildingId Complete:(void(^)(NSArray *lineOptionArray))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(nil);}return;}
    
    [[WMHttpTool shareHttpTool] getWithUrl:[YWCommonTool getAllInspectionLineUrl] params:@{@"buildingId": buildingId?:@""} success:^(NSHTTPURLResponse* response, id json) {
        NSArray* inspectionLineOptionArray = [YWInspectionLineOption mj_objectArrayWithKeyValuesArray:json];
        //数据过来不完整（只有id和名字），不保存线路
        
        if (complete) {
            complete(inspectionLineOptionArray);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(nil);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (void)requestInspectionLineWithInspectionLineId:(NSInteger)lineId Complete:(void(^)(YWInspectionLineModel *inspectionLine))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(nil);}return;}
    
    NSString* url = [NSString stringWithFormat:@"%@/%ld", [YWCommonTool getOneInspectionLineUrl], (long)lineId];
    YWLog(@"请求单条巡查路线:%@",url);
    [[WMHttpTool shareHttpTool] getWithUrl:url params:nil success:^(NSHTTPURLResponse* response, id json) {
        YWInspectionLineModel* inspectionLine = [YWInspectionLineModel mj_objectWithKeyValues:json];
        //保存线路，线路与巡查任务没有关联，任务id就用-100
        if (inspectionLine) {
            [[YWInspectionMissionDBManager shareManager] updateInspectionLine:inspectionLine];
        }
        if (complete) {
            complete(inspectionLine);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(nil);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (void)postInspectionMissionWithParams:(NSDictionary*)params Complete:(void(^)(BOOL success))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);}return;}
    
    [[WMHttpTool shareHttpTool] postWithUrl:[YWCommonTool getInspectionMissionUrl] params:params success:^(NSHTTPURLResponse* response, id json) {
        YWInspectionMissionModel* inspectionMission = [YWInspectionMissionModel mj_objectWithKeyValues:json];
        //保存任务
        if (inspectionMission) {
            [[YWInspectionMissionManager shareManager] saveInspectionMissionWithArray:@[inspectionMission]];
            //因为任务里过来的路线只有id和name，所以需要再请求完整路线
            [[YWInspectionMissionManager shareManager] requestInspectionLineWithInspectionLineId:inspectionMission.inspectionLine.inspectionLineId Complete:^(YWInspectionLineModel *inspectionLine) {
                if (inspectionLine) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:KRefreshAssignInspectionMissionNotification object:nil];
                }
                if (complete) {
                    complete(YES);
                }
            }];
        }else{
            if (complete) {
                complete(YES);
            }
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }else{
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"kTextAssignFailed", nil)];
        }
        if (complete) {
            complete(NO);
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (void)requestDeleteInspectionMission:(NSInteger)inspectionMissionId completeBlock:(void (^)(BOOL))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);}return;}
    
    NSString *url = [NSString stringWithFormat:@"%@/%ld",[YWCommonTool getInspectionMissionUrl],(long)inspectionMissionId];
    YWLog(@"%@",url);
    [[WMHttpTool shareHttpTool] deleteWithUrl:url params:nil success:^(NSHTTPURLResponse* response, id json) {
        BOOL success = [[YWInspectionMissionManager shareManager] updateInspectionMissionDeleteStatusWithMissionId:inspectionMissionId];
        if (success) {
            [[YWEwinManager shareManager] subtractTotalCountWithType:YWUnReadCountTypeInspection];
            [[NSNotificationCenter defaultCenter] postNotificationName:KRefreshDeleteInspectionMissionNotification object:nil];
        }
        if (complete) {
            complete(YES);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }else{
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"deleteFailed", nil)];
        }
        if (complete) {
            complete(NO);
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (void)requestModifyInspectionMission:(NSDictionary*)params completeBlock:(void (^)(BOOL))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);}return;}
    
    [[WMHttpTool shareHttpTool] putWithUrl:[YWCommonTool getInspectionMissionUrl] params:params success:^(NSHTTPURLResponse* response, id json) {
        if (complete) {
            complete(YES);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }else{
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"modifyFailed", nil)];
        }
        if (complete) {
            complete(NO);
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (void)createInspectionLine:(NSDictionary *)params completeBlock:(void (^)(NSInteger))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(0);}return;}
    
    YWLog(@"createInspectionLine --- %@",params);
    [[WMHttpTool shareHttpTool] postWithUrl:[YWCommonTool getOneInspectionLineUrl] params:params success:^(NSHTTPURLResponse* response, id json) {
        if (complete) {
            complete(response.statusCode);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }else{
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"createLineFailed", nil)];
        }
        if (complete) {
            complete(response.statusCode);
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (void)deleteInspectionLineWithLineId:(NSInteger)inspectionLineId completeBlock:(void (^)(NSInteger))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(0);}return;}
    
    YWLog(@"deleteInspectionLine %ld",(long)inspectionLineId);
    NSString *url = [NSString stringWithFormat:@"%@/%ld",[YWCommonTool getOneInspectionLineUrl],(long)inspectionLineId];
    [[WMHttpTool shareHttpTool] deleteWithUrl:url params:nil success:^(NSHTTPURLResponse *response, id json) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KRefreshDeleteInspectionLineNotification object:@(inspectionLineId)];
        if (complete) {
            complete(response.statusCode);
        }
    } failure:^(NSHTTPURLResponse *response, NSError *error) {
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }else if (response.statusCode == 403){
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"deleteFailedBecauseOfUnfinishMission", nil)];
        }else{
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"deleteFailed", nil)];
        }
        if (complete) {
            complete(response.statusCode);
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}
- (void)modifyInspectionLine:(NSDictionary *)params completeBlock:(void (^)(BOOL))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);}return;}
    
    YWLog(@"modifyInspectionLine params --- %@",params);
    [[WMHttpTool shareHttpTool] putWithUrl:[YWCommonTool getOneInspectionLineUrl] params:params success:^(NSHTTPURLResponse *response, id json) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KRefreshModifyInspectionLineNotification object:nil];
        if (complete) {
            complete(YES);
        }
    } failure:^(NSHTTPURLResponse *response, NSError *error) {
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }else{
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"modifyLineFailed", nil)];
        }
        if (complete) {
            complete(NO);
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (void)requestInspectionMissionWithPage:(NSInteger)page pageSize:(NSInteger)pageSize complete:(void (^)(BOOL))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);}return;}
    
    NSDictionary *params = [NSMutableDictionary dictionary];
    if (page) {
        [params setValue:@(page) forKey:@"page"];
    }
    if (pageSize) {
        [params setValue:@(pageSize) forKey:@"pageSize"];
    }
    YWLog(@"%@",params);
    [[WMHttpTool shareHttpTool] getWithUrl:[YWCommonTool getInspectionMissionUrl] params:params success:^(NSHTTPURLResponse* response, id json) {
        NSArray* inspectionMission = [YWInspectionMissionModel mj_objectArrayWithKeyValuesArray:json];
        //保存任务
        [[YWInspectionMissionManager shareManager] saveInspectionMissionWithArray:inspectionMission];
        
        if (complete) {
            complete(YES);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(NO);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }else{
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"requestFailed", nil)];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (void)requestInspectionMissionWithMissionId:(NSInteger)missionId Complete:(void(^)(YWInspectionMissionModel* inspectionMission))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(nil);}return;}
    
     NSString* url = [NSString stringWithFormat:@"%@/%ld", [YWCommonTool getInspectionMissionUrl], (long)missionId];
    [[WMHttpTool shareHttpTool] getWithUrl:url params:nil success:^(NSHTTPURLResponse* response, id json) {
        YWInspectionMissionModel* inspectionMission = [YWInspectionMissionModel mj_objectWithKeyValues:json];
        //保存任务
        if (inspectionMission) {
            [[YWInspectionMissionManager shareManager] saveInspectionMissionWithArray:@[inspectionMission]];
        }
        
        if (complete) {
            complete(inspectionMission);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(nil);
        }
//        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
//            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
//        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (void)requestInspectionLineRecordWithPage:(NSInteger)page pageSize:(NSInteger)pageSize complete:(void (^)(BOOL))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);}return;}
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (page) {
        [params setValue:@(page) forKey:@"page"];
    }
    if (pageSize) {
        [params setValue:@(pageSize) forKey:@"pageSize"];
    }

    NSString *url = [YWCommonTool getInspectionRecordUrl];
    YWLog(@"url:%@,params:%@",url,params);
    [[WMHttpTool shareHttpTool] getWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        NSArray* inspectionLineRecord = [YWInspectionLineRecord mj_objectArrayWithKeyValuesArray:json];
        
        NSMutableArray *missionArray = [NSMutableArray array];
        [inspectionLineRecord enumerateObjectsUsingBlock:^(YWInspectionLineRecord*  _Nonnull lineRecord, NSUInteger idx, BOOL * _Nonnull stop) {
            YWInspectionMissionModel *inspectionMission = [[YWInspectionMissionModel alloc] init];
            inspectionMission.inspectionMissionId = lineRecord.inspectionMissionId;
            inspectionMission.creator = lineRecord.missionCreator;
            inspectionMission.buildingId = lineRecord.buildingId;
            inspectionMission.missionSequence = lineRecord.missionSequence;
            inspectionMission.status = -2;
            [missionArray addObject:inspectionMission];
        }];
        [[YWInspectionMissionManager shareManager] updateInspectionLineRecordWithNewWorkData:inspectionLineRecord];
        //保存任务
        [[YWInspectionMissionManager shareManager] saveInspectionMissionWithArray:missionArray];
        if (complete) {
            complete(YES);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(NO);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }else{
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"requestFailed", nil)];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (void)requestInspectionLineRecordWithPage:(NSInteger)page pageSize:(NSInteger)pageSize inspectionMissionId:(NSInteger)inspectionMissionId inspectionLineId:(NSInteger)inspectionLineId WithComplete:(void(^)(BOOL success))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);}return;}
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (inspectionMissionId > 0) {
        [params setObject:@(inspectionMissionId) forKey:@"inspectionMissionId"];
    }
    if (inspectionLineId) {
        [params setObject:@(inspectionLineId) forKey:@"inspectionLineId"];
    }
    if (page) {
        [params setObject:@(page) forKey:@"page"];
    }
    if (pageSize) {
        [params setObject:@(pageSize) forKey:@"pageSize"];
    }
    NSString *url = [YWCommonTool getInspectionRecordUrl];
    YWLog(@"url:%@,params:%@",url,params);
    [[WMHttpTool shareHttpTool] getWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSArray* inspectionLineRecord = [YWInspectionLineRecord mj_objectArrayWithKeyValuesArray:json];
            [[YWInspectionMissionManager shareManager] updateInspectionLineRecordWithNewWorkData:inspectionLineRecord];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (complete) {
                    complete(YES);
                }
            });
        });
        
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(NO);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }else{
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"requestFailed", nil)];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (void)requestInspectionEquipmentRecord:(NSString*)uniqueTag type:(YWInspectionEquipmentRecordType)type WithComplete:(void(^)(BOOL success))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);}return;}
    
    NSString *url = [NSString stringWithFormat:@"%@/%@",[YWCommonTool getInspectionRecordUrl],uniqueTag];
    YWLog(@"请求所有巡查点的记录%@",url);
    [[WMHttpTool shareHttpTool] getWithUrl:url params:nil success:^(NSHTTPURLResponse* response, id json) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            YWInspectionEquipmentRecordJson* equipmentRecordJson = [YWInspectionEquipmentRecordJson mj_objectWithKeyValues:json];
            __block NSMutableArray *totalEquipmentRecordArray = [NSMutableArray array];
            __block NSMutableArray *picturesArray = [NSMutableArray array];
            __block YWInspectionEquipmentRecord *equRecord = nil;
            
            [equipmentRecordJson.allKindRecord enumerateObjectsUsingBlock:^(YWInspectionEquipmentRecord*  _Nonnull detailPointRecord, NSUInteger idx, BOOL * _Nonnull stop) {
                equRecord = [[YWInspectionEquipmentRecord alloc]init];
                equRecord.inspectionLineId = equipmentRecordJson.inspectionLine.inspectionLineId;
                equRecord.inspectionMissionId = equipmentRecordJson.inspectionMissionId;
                equRecord.uniqueTag = equipmentRecordJson.uniqueTag;
                equRecord.detailUniqueTag = detailPointRecord.detailUniqueTag;
                equRecord.executeTime = detailPointRecord.executeTime;
                equRecord.executor = detailPointRecord.executor;
                equRecord.note = detailPointRecord.note;
                equRecord.equipment = detailPointRecord.equipment;
                equRecord.recordType = type;
                equRecord.locationId = detailPointRecord.locationId;
                if (type==YWInspectionEquipmentRecordTypeEquipment && equRecord.equipment) {
                    equRecord.equipmentRecordId = [NSString stringWithFormat:@"%@_%@", equRecord.uniqueTag,equRecord.equipment.equipmentId];
                }else{
                    equRecord.equipmentRecordId = [NSString stringWithFormat:@"%@_%ld", equRecord.uniqueTag,(long)equRecord.locationId];
                }
                
                equRecord.equipmentFields = detailPointRecord.equipmentFields;
                equRecord.status = detailPointRecord.status;
                equRecord.uploadStatus = YWPatrolPointRecordUploadStatusFinished;
                [detailPointRecord.pictures enumerateObjectsUsingBlock:^(YWPatrolPicture*  _Nonnull patrolPicture, NSUInteger idx, BOOL * _Nonnull stop) {
                    patrolPicture.recordId = equRecord.equipmentRecordId;
                    patrolPicture.pictureId = [YWCommonTool randStringId];
                    patrolPicture.pictureName = @"";
                    patrolPicture.isLocalImage = NO;
                    patrolPicture.uploadStatus = YWPictureRecordUploadStatusSuccess;
                    patrolPicture.recordType = YWPictureRecordTypeInspectionMission;
                    [picturesArray addObject:patrolPicture];
                }];
                [totalEquipmentRecordArray addObject:equRecord];
                //是否建立与报障的关联
                [detailPointRecord.posTroubleArray enumerateObjectsUsingBlock:^(YWTroubleIdJson*  _Nonnull troubleIdJson, NSUInteger idx, BOOL * _Nonnull stop) {
                    if (![[YWMissionManager shareManager] isExistRelWithTroubleId:troubleIdJson.troubleId detailUniqueTag:equRecord.detailUniqueTag]) {
                        [[YWMissionManager shareManager] saveRecordAndPostTroubleRelWithtroubleId:troubleIdJson.troubleId detailUniqueTag:equRecord.detailUniqueTag];
                    }
                }];
                
            }];
            [[YWInspectionMissionManager shareManager] updateInspectionEquipmentRecordWithArray:totalEquipmentRecordArray];
            [[YWKeepWatchMissionManager shareManager] updatePatrolPictureWithNewWorkData:picturesArray];
            
            if (totalEquipmentRecordArray.count) {
                NSMutableArray *fieldRecorsArray = [NSMutableArray array];
                [totalEquipmentRecordArray enumerateObjectsUsingBlock:^(YWInspectionEquipmentRecord*  _Nonnull equRecord, NSUInteger idx, BOOL * _Nonnull stop) {
                    [equRecord.equipmentFields enumerateObjectsUsingBlock:^(YWEquipmentFieldRecord*  _Nonnull fieldRecord, NSUInteger idx, BOOL * _Nonnull stop) {
                        fieldRecord.uniqueTag = equRecord.equipmentRecordId;
                        fieldRecord.maintenanceTypeId = YWMaintenanceTypePatrol;
                        [fieldRecorsArray addObject:fieldRecord];
                    }];
                }];
                [[YWMissionManager shareManager] updateEquipmentFieldRecords:fieldRecorsArray];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                if (complete) {
                    complete(YES);
                }
            });
        });
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(NO);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}


- (void)requestInspectionLocationRecord:(NSInteger)locationId page:(NSInteger)page pageSize:(NSInteger)pageSize complete:(void (^)(BOOL))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);}return;}
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:@(locationId) forKey:@"locationId"];
    if (page) {
        [params setObject:@(page) forKey:@"page"];
    }
    if (pageSize) {
        [params setObject:@(pageSize) forKey:@"pageSize"];
    }
    NSString *url = [YWCommonTool submitInspectionLocationRecordUrl];
    YWLog(@"url:%@,params:%@",url,params);
    
    [[WMHttpTool shareHttpTool] getWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        NSArray *inspectionLcationArray = [YWInspectionLocationRecordJson mj_objectArrayWithKeyValuesArray:json];
        __block NSMutableArray *totalPointRecordArray = [NSMutableArray array];
        __block NSMutableArray *picturesArray = [NSMutableArray array];
        __block YWInspectionEquipmentRecord *pointRecord = nil;
        
        [inspectionLcationArray enumerateObjectsUsingBlock:^(YWInspectionLocationRecordJson*  _Nonnull locationRecordJson, NSUInteger idx, BOOL * _Nonnull stop) {
            pointRecord = [[YWInspectionEquipmentRecord alloc]init];
            pointRecord.inspectionLineId = 0;
            pointRecord.inspectionMissionId = 0;
            pointRecord.uniqueTag = locationRecordJson.uniqueTag;
            pointRecord.detailUniqueTag = locationRecordJson.detailUniqueTag;
            
            pointRecord.executeTime = locationRecordJson.executeTime;
            pointRecord.executor = locationRecordJson.executor;
            pointRecord.locationId = locationId;
            pointRecord.note = locationRecordJson.note;
            pointRecord.equipmentRecordId = [NSString stringWithFormat:@"%@_%ld", locationRecordJson.uniqueTag,(long)locationId];
            pointRecord.recordType = YWInspectionEquipmentRecordTypeLocation;
            
            pointRecord.status = locationRecordJson.status;
            pointRecord.uploadStatus = YWPatrolPointRecordUploadStatusFinished;
            
            [locationRecordJson.pictures enumerateObjectsUsingBlock:^(YWPatrolPicture*  _Nonnull patrolPicture, NSUInteger idx, BOOL * _Nonnull stop) {
                patrolPicture.recordId = pointRecord.equipmentRecordId;
                patrolPicture.pictureId = [YWCommonTool randStringId];
                patrolPicture.pictureName = @"";
                patrolPicture.isLocalImage = NO;
                patrolPicture.uploadStatus = YWPictureRecordUploadStatusSuccess;
                patrolPicture.recordType = YWPictureRecordTypeInspectionMission;
                [picturesArray addObject:patrolPicture];
            }];
            [totalPointRecordArray addObject:pointRecord];
            //是否建立与报障的关联
            [locationRecordJson.posTroubleArray enumerateObjectsUsingBlock:^(YWTroubleIdJson*  _Nonnull troubleIdJson, NSUInteger idx, BOOL * _Nonnull stop) {
                if (![[YWMissionManager shareManager] isExistRelWithTroubleId:troubleIdJson.troubleId detailUniqueTag:pointRecord.detailUniqueTag]) {
                    [[YWMissionManager shareManager] saveRecordAndPostTroubleRelWithtroubleId:troubleIdJson.troubleId detailUniqueTag:pointRecord.detailUniqueTag];
                }
            }];
        }];
        //不是全量字段更新
        [[YWInspectionMissionManager shareManager] updateLocationInspectionRecordWithArray:totalPointRecordArray];
        [[YWKeepWatchMissionManager shareManager] updatePatrolPictureWithNewWorkData:picturesArray];
        if (complete) {
            complete(YES);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(NO);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (void)requestInspectionMissionStatusWithIds:(NSString *)ids Complete:(void (^)(BOOL))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);}return;}
    
    [[WMHttpTool shareHttpTool] getWithUrl:[YWCommonTool getInspectionMissionStatusUrl] params:@{@"missionIds" : ids?:@""} success:^(NSHTTPURLResponse* response, id json) {
        NSArray* missions = [YWInspectionMissionModel mj_objectArrayWithKeyValuesArray:json];
        [missions enumerateObjectsUsingBlock:^(YWInspectionMissionModel*  _Nonnull inspectionMission, NSUInteger idx, BOOL * _Nonnull stop) {
            if (inspectionMission.status == -1) {
                [self updateInspectionMissionDeleteStatusWithMissionId:inspectionMission.inspectionMissionId];
            }else{
                YWLoginUser *currentUser = [YWLoginTool loginUser];
                if (inspectionMission.creator.uniqueId != currentUser.uniqueId && ![YWCommonTool containSelfInHandlers:inspectionMission.executors] && ![inspectionMission.observerIds containsString:@(currentUser.uniqueId).stringValue]){
                    [self updateInspectionMissionDeleteStatusWithMissionId:inspectionMission.inspectionMissionId];
                }
            }
        }];
        
        if (complete) {
            complete(YES);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(NO);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}


- (void)startUploadInspectionRecords:(NSArray*)records pictures:(NSArray*)pictures WithType:(YWInspectionEquipmentRecordType)type{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        __block NSMutableArray *postTroublePictures = [NSMutableArray array];
        [records enumerateObjectsUsingBlock:^(YWInspectionEquipmentRecord*  _Nonnull record, NSUInteger idx, BOOL * _Nonnull stop) {
            [record.posTroubleArray enumerateObjectsUsingBlock:^(YWReportTroubleModel*  _Nonnull reportTroubleModel, NSUInteger idx, BOOL * _Nonnull stop) {
                NSArray *pictures = [[YWDBTool shareDBTool] picturesWithMissionId:reportTroubleModel.troubleId maintenanceType:reportTroubleModel.maintenanceTypeId];
                [postTroublePictures addObjectsFromArray:pictures];
            }];
        }];
        [self handleWithPictures:pictures postTroublePictures:postTroublePictures recordArray:records type:type];
    });
}

- (void)uploadFailInspectionRecords{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if (![YWLoginTool isLogin]) {
            return;
        }
        if (isUploading == YES) {
            return;
        }
        isUploading = YES;
        
        //设备记录
        [self uploadFailEquipmentInspectionRecords];
        //位置记录
        [self uploadFailLocationInspectionRecords];
        
        isUploading = NO;
        dispatch_async(dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter] postNotificationName:KPushBackgroundUploadRecordSuccessNotification object:nil];
        });
    });
}

- (void)uploadFailEquipmentInspectionRecords{
    NSArray* uploadFailEquipmentRecords = [self inspectionEquipmentRecordsWithUploadStatusFailWithType:YWInspectionEquipmentRecordTypeEquipment];
    [uploadFailEquipmentRecords enumerateObjectsUsingBlock:^(NSArray*  _Nonnull array, NSUInteger idx, BOOL * _Nonnull stop) {
        [self commitEquipmentRecordWithArray:array];
    }];
}

- (void)uploadFailLocationInspectionRecords{
    NSArray* uploadFailLocationRecords = [self inspectionEquipmentRecordsWithUploadStatusFailWithType:YWInspectionEquipmentRecordTypeLocation];
    [uploadFailLocationRecords enumerateObjectsUsingBlock:^(NSArray*  _Nonnull array, NSUInteger idx, BOOL * _Nonnull stop) {
        [self commitLocationRecordWithDelay:array];
    }];
}

- (void)commitEquipmentRecordWithArray:(NSArray*)equRecordArray{
    __block NSMutableArray *allPictures = [NSMutableArray array];
    __block NSMutableArray *postTroublePictures = [NSMutableArray array];
    [equRecordArray enumerateObjectsUsingBlock:^(YWInspectionEquipmentRecord*  _Nonnull equRecord, NSUInteger idx, BOOL * _Nonnull stop) {
        //运行参数
        equRecord.equipmentFields = [[YWMissionManager shareManager]equipmentFieldRecordsWithUniqueTag:equRecord.equipmentRecordId maintenanceTypeId:YWMaintenanceTypePatrol];
        //图片
        NSArray* pictures = [[YWKeepWatchMissionManager shareManager] recordPictureWithRecordId:equRecord.equipmentRecordId recordType:YWPictureRecordTypeInspectionMission];
        [allPictures addObjectsFromArray:pictures];
        //关联的报障
        equRecord.posTroubleArray = [[YWMissionManager shareManager] postTroubleArrayWithDetailUniqueTag:equRecord.detailUniqueTag];
        
        [equRecord.posTroubleArray enumerateObjectsUsingBlock:^(YWReportTroubleModel*  _Nonnull reportTroubleModel, NSUInteger idx, BOOL * _Nonnull stop) {
            NSArray *pictures = [[YWDBTool shareDBTool] picturesWithMissionId:reportTroubleModel.troubleId maintenanceType:reportTroubleModel.maintenanceTypeId];
            [postTroublePictures addObjectsFromArray:pictures];
        }];
    }];
    [self handleWithPictures:allPictures postTroublePictures:postTroublePictures recordArray:equRecordArray type:YWInspectionEquipmentRecordTypeEquipment];
}

- (void)commitLocationRecordWithDelay:(NSArray*)equRecordArray{
    __block NSMutableArray *allPictures = [NSMutableArray array];
    __block NSMutableArray *postTroublePictures = [NSMutableArray array];
    [equRecordArray enumerateObjectsUsingBlock:^(YWInspectionEquipmentRecord*  _Nonnull equRecord, NSUInteger idx, BOOL * _Nonnull stop) {
        NSArray* pictures = [[YWKeepWatchMissionManager shareManager] recordPictureWithRecordId:equRecord.equipmentRecordId recordType:YWPictureRecordTypeInspectionMission];
        [allPictures addObjectsFromArray:pictures];
        //关联的报障
        equRecord.posTroubleArray = [[YWMissionManager shareManager] postTroubleArrayWithDetailUniqueTag:equRecord.detailUniqueTag];
        
        [equRecord.posTroubleArray enumerateObjectsUsingBlock:^(YWReportTroubleModel*  _Nonnull reportTroubleModel, NSUInteger idx, BOOL * _Nonnull stop) {
            NSArray *pictures = [[YWDBTool shareDBTool] picturesWithMissionId:reportTroubleModel.troubleId maintenanceType:reportTroubleModel.maintenanceTypeId];
            [postTroublePictures addObjectsFromArray:pictures];
        }];
    }];
    [self handleWithPictures:allPictures postTroublePictures:postTroublePictures recordArray:equRecordArray type:YWInspectionEquipmentRecordTypeLocation];
}

- (void)handleWithPictures:(NSArray *)allPictures postTroublePictures:(NSArray*)postTroublePictures recordArray:(NSArray*)recordArray type:(YWInspectionEquipmentRecordType)recordType{
    if (recordArray.count == 0) {
        return;
    }
    dispatch_group_enter(self.group);
    if (allPictures.count>0 || postTroublePictures.count>0) {
        [self uploadPictures:allPictures postTroublePicture:postTroublePictures complete:^(BOOL isError) {
            [self uploadCompleteHandleWithRecords:recordArray type:recordType error:isError];
        }];
    }else{
        [self uploadCompleteHandleWithRecords:recordArray type:recordType error:NO];
    }
    dispatch_group_wait(self.group, DISPATCH_TIME_FOREVER);
}

- (void)uploadPictures:(NSArray*)recordPictures postTroublePicture:(NSArray*)postTroublePictures complete:(void (^)(BOOL isError))completeBlock{
    __block BOOL error = NO;
    //__block NSArray *successRecordPic = nil;
    [[YWResourceManager shareManager]
     uploadPatrolPictureToAliyunOSS:recordPictures
     complete:^(BOOL isError, NSArray* uploadPictures) {
         //successRecordPic = uploadPictures;
         error = isError;
         if (!isError) {
             [self updatePatrolPictureWithArray:uploadPictures];
             [[YWResourceManager shareManager]
              uploadLocalPictureToAliyunOSS:postTroublePictures
              isAvatar:NO
              complete:^(BOOL isError, NSArray* uploadPictures) {
                  error = isError;
                  if (!isError) {
                      //报障的图片不在bloc里返回，因为如果有多个报障，图片数组不能和报障信息一一对应，会造成图片混乱
                      [[YWResourceManager shareManager] savePicturesToDBWithArray:uploadPictures];
                  }
                  if (completeBlock) {
                      completeBlock(error);
                  }
              }];
         }else{
             if (completeBlock) {
                 completeBlock(error);
             }
         }
     }];
}

- (void)uploadCompleteHandleWithRecords:(NSArray*)records type:(YWInspectionEquipmentRecordType)type error:(BOOL)isError{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if (!isError) {
            if (type==YWInspectionEquipmentRecordTypeEquipment) {
                //设备记录
                [self submitInspectionEquipmentRecords:records];
            }else{
                //位置记录
                [self submitInspectionLocationRecords:records];
            }
        }else{
            [records enumerateObjectsUsingBlock:^(YWInspectionEquipmentRecord* _Nonnull record, NSUInteger idx, BOOL* _Nonnull stop) {
                [self updateInspectionEquipmentRecordUploadStatus:YWInspectionEquipmentRecordUploadStatusUnFinished inspectionEquipmentRecordId:record.equipmentRecordId];
            }];
            dispatch_group_leave(self.group);
        }
    });
}

- (void)submitInspectionEquipmentRecords:(NSArray*)records{
    NSDictionary *headers = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headers;
    if (headers == nil) {dispatch_group_leave(self.group);return;}
    
    NSMutableDictionary* params = [NSMutableDictionary dictionary];
    __block YWBuilding *building = nil;
    [records enumerateObjectsUsingBlock:^(YWInspectionEquipmentRecord* _Nonnull record, NSUInteger idx, BOOL* _Nonnull stop) {
        building = [[YWBuildingManager shareManager] buildingWithEquipmentId:record.equipment.equipmentId];
        if (building == nil) {
            building = [[YWBuildingManager shareManager] buildingWithLocationId:record.locationId];
        }
        [params setValue:@(record.inspectionMissionId) forKey:[NSString stringWithFormat:@"records[%lu].inspectionMissionId", (unsigned long)idx]];
        [params setValue:@(record.inspectionLineId) forKey:[NSString stringWithFormat:@"records[%lu].inspectionLine.inspectionLineId", (unsigned long)idx]];
        
        [params setValue:building.buildingId?:@"" forKey:[NSString stringWithFormat:@"records[%lu].buildingId", (unsigned long)idx]];
        [params setValue:record.note?:@"" forKey:[NSString stringWithFormat:@"records[%lu].note", (unsigned long)idx]];
        [params setValue:record.equipment.equipmentId?:@"" forKey:[NSString stringWithFormat:@"records[%lu].equipment.equipmentId", (unsigned long)idx]];
        [params setValue:@(record.status) forKey:[NSString stringWithFormat:@"records[%lu].resultCode", (unsigned long)idx]];
        [params setValue:record.uniqueTag forKey:[NSString stringWithFormat:@"records[%lu].uniqueTag", (unsigned long)idx]];
        [params setValue:record.detailUniqueTag?:[NSString stringWithFormat:@"%@_%@",record.uniqueTag,record.equipment.equipmentId] forKey:[NSString stringWithFormat:@"records[%lu].detailUniqueTag", (unsigned long)idx]];
        
        NSArray* recordPic = [[YWKeepWatchMissionManager shareManager] recordPictureWithRecordId:record.equipmentRecordId recordType:YWPictureRecordTypeInspectionMission];
        [recordPic enumerateObjectsUsingBlock:^(YWPatrolPicture* _Nonnull picture, NSUInteger index, BOOL* _Nonnull stop) {
            [params setValue:picture.bigUrl ?: @"" forKey:[NSString stringWithFormat:@"records[%lu].pictures[%lu].url", (unsigned long)idx,(unsigned long)index]];
            [params setValue:picture.smallUrl ?: @"" forKey:[NSString stringWithFormat:@"records[%lu].pictures[%lu].thumbnailUrl", (unsigned long)idx,(unsigned long)index]];
            [params setValue:picture.smallUrl ?: @"" forKey:[NSString stringWithFormat:@"records[%lu].pictures[%lu].previewUrl", (unsigned long)idx,(unsigned long)index]];
        }];
        //自定义属性
        [record.equipmentFields enumerateObjectsUsingBlock:^(YWEquipmentFieldRecord*  _Nonnull fieldRecord, NSUInteger cusIdx, BOOL * _Nonnull stop) {
            if (fieldRecord.fieldTypeId == YWEquipmentFieldTypeIdDownSelect) {
                [params setValue:@(fieldRecord.fieldId) forKey:[NSString stringWithFormat:@"records[%lu].equipmentFields[%lu].fieldId", (unsigned long)idx, (unsigned long)cusIdx]];
                [params setValue:@(fieldRecord.fieldOption.fieldOptionId) forKey:[NSString stringWithFormat:@"records[%lu].equipmentFields[%lu].fieldValue", (unsigned long)idx, (unsigned long)cusIdx]];
            }else{
                if (fieldRecord.fieldValue.length>0) {
                    [params setValue:@(fieldRecord.fieldId) forKey:[NSString stringWithFormat:@"records[%lu].equipmentFields[%lu].fieldId", (unsigned long)idx, (unsigned long)cusIdx]];
                    [params setValue:fieldRecord.fieldValue ?: @"" forKey:[NSString stringWithFormat:@"records[%lu].equipmentFields[%lu].fieldValue", (unsigned long)idx, (unsigned long)cusIdx]];
                }
            }
        }];
        //报障信息
        [record.posTroubleArray enumerateObjectsUsingBlock:^(YWReportTroubleModel*  _Nonnull reportTroubleModel, NSUInteger troubleIdx, BOOL * _Nonnull stop) {
            //报障信息
            [params setValue:reportTroubleModel.uniqueTag?:@"" forKey:[NSString stringWithFormat:@"records[%lu].troubles[%lu].uniqueTag",(unsigned long)idx,(unsigned long)troubleIdx]];
            YWEquipment* equipment = reportTroubleModel.equipment;
            if (equipment && equipment.equipmentTypeId > 0) {
                [params setValue:@(equipment.locationId) forKey:[NSString stringWithFormat:@"records[%lu].troubles[%lu].location.locationId",(unsigned long)idx,(unsigned long)troubleIdx]];
                [params setValue:@(equipment.equipmentTypeId) forKey:[NSString stringWithFormat:@"records[%lu].troubles[%lu].equipmentType.equipmentTypeId",(unsigned long)idx,(unsigned long)troubleIdx]];
                [params setValue:equipment.equipmentId ?: @"" forKey:[NSString stringWithFormat:@"records[%lu].troubles[%lu].equipment.equipmentId",(unsigned long)idx,(unsigned long)troubleIdx]];
            }else{
                NSInteger locationId = reportTroubleModel.location.locationId;
                if (locationId==0 && records.count>0) {
                    YWInspectionEquipmentRecord *record = records[0];
                    locationId = record.equipment.locationId;
                }
                [params setValue:@(locationId) forKey:[NSString stringWithFormat:@"records[%lu].troubles[%lu].location.locationId",(unsigned long)idx,(unsigned long)troubleIdx]];
            }
            
            [params setValue:reportTroubleModel.qrcodeId ?: @"" forKey:[NSString stringWithFormat:@"records[%lu].troubles[%lu].qrcodeId",(unsigned long)idx,(unsigned long)troubleIdx]];
            [params setValue:reportTroubleModel.note?:@"" forKey:[NSString stringWithFormat:@"records[%lu].troubles[%lu].note",(unsigned long)idx,(unsigned long)troubleIdx]];
            YWBuilding* building = reportTroubleModel.building;
            
            if (building==nil && reportTroubleModel.equipment.equipmentId.length) {
                building = [[YWBuildingManager shareManager] buildingWithEquipmentId:reportTroubleModel.equipment.equipmentId];
            }
            if (building == nil && reportTroubleModel.location.locationId>0) {
                building = [[YWBuildingManager shareManager] buildingWithLocationId:reportTroubleModel.location.locationId];
            }
            [params setValue:building.buildingId ?: @"" forKey:[NSString stringWithFormat:@"records[%lu].troubles[%lu].building.buildingId",(unsigned long)idx,(unsigned long)troubleIdx]];
            NSArray *troublePicureArray = [[YWDBTool shareDBTool] picturesWithMissionId:reportTroubleModel.troubleId maintenanceType:reportTroubleModel.maintenanceTypeId];
            [troublePicureArray enumerateObjectsUsingBlock:^(YWPicture* _Nonnull picture, NSUInteger picIdx, BOOL* _Nonnull stop) {
                [params setValue:picture.bigPictureUrl ?: @"" forKey:[NSString stringWithFormat:@"records[%lu].troubles[%lu].pictures[%lu].url",(unsigned long)idx,(unsigned long)troubleIdx,(unsigned long)picIdx]];
                [params setValue:picture.smallPictureUrl ?: @"" forKey:[NSString stringWithFormat:@"records[%lu].troubles[%lu].pictures[%lu].thumbnailUrl",(unsigned long)idx,(unsigned long)troubleIdx,(unsigned long)picIdx]];
                [params setValue:picture.smallPictureUrl ?: @"" forKey:[NSString stringWithFormat:@"records[%lu].troubles[%lu].pictures[%lu].previewUrl",(unsigned long)idx,(unsigned long)troubleIdx,(unsigned long)picIdx]];
            }];
        }];
        
        long long executeTime = [YWCommonTool numberWithTime:record.executeTime];
        [params setValue:@(executeTime) forKey:[NSString stringWithFormat:@"records[%lu].clientExecuteTime", (unsigned long)idx]];
        long long nowTime = [YWCommonTool numberWithTime:[[NSDate date] timeIntervalSince1970]*1000];
        [params setValue:@(nowTime) forKey:[NSString stringWithFormat:@"records[%lu].clientCurrentTime", (unsigned long)idx]];
    }];
    NSString * url = [YWCommonTool submitInspectionEquipmentRecordUrl];
    
    NSString *logTag = [YWCommonTool randStringId];
    //保存请求前的参数日志
    NSMutableDictionary * logDic = [[YWLogRecordTool shareLogRecordManager] getLogDictionaryWithModule:@"设备巡查" interface:url params:params headers:headers tag:logTag];
    [[YWLogRecordTool shareLogRecordManager] saveLocalPatameterLog:logDic];
    
    YWLog(@"%@", params);
    
    [[WMHttpTool shareHttpTool] postWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        YWLog(@"提交设备巡查记录成功");
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [records enumerateObjectsUsingBlock:^(YWInspectionEquipmentRecord* _Nonnull record, NSUInteger idx, BOOL* _Nonnull stop) {
                [self updateInspectionEquipmentRecordUploadStatus:YWInspectionEquipmentRecordUploadStatusFinished inspectionEquipmentRecordId:record.equipmentRecordId];
            }];
            NSArray* reportTroubleArray = [YWReportTroubleModel mj_objectArrayWithKeyValuesArray:[json objectForKey:@"troubles"]];
            if (reportTroubleArray.count) {
                [reportTroubleArray enumerateObjectsUsingBlock:^(YWReportTroubleModel*  _Nonnull reportTrouble, NSUInteger idx, BOOL * _Nonnull stop) {
                    //保存流转信息
                    [[YWCirculationManager shareManager] updateCirculationInfoWithArray:reportTrouble.circulationInfos];
                    //更新关联表的troubleId
                    [[YWMissionManager shareManager] updateRecordAndPostTroubleRelTableUniqueTag:reportTrouble.uniqueTag newTroubleId:reportTrouble.troubleId];
                    //修改本地的troubleId
                    [[YWMissionManager shareManager] updatePostTroubleId:reportTrouble uniqueTag:reportTrouble.uniqueTag];
                }];
            }
            //保存请求成功的参数日志
            NSMutableDictionary * successDic =
            [[YWLogRecordTool shareLogRecordManager] successOrFailedLogDicWith:logDic statusCode:response.statusCode errorInfo:@"无" logTag:logTag];
            [[YWLogRecordTool shareLogRecordManager] saveLocalPatameterLog:successDic];
            dispatch_group_leave(self.group);
        });
        
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            YWLog(@"%s,error:%@", __func__, error.localizedDescription);
            //保存请求失败的参数日志
            NSString * result = [NSString stringWithFormat:@"%s,error:%@", __func__, error.localizedDescription];
            NSMutableDictionary * failedDic = [[YWLogRecordTool shareLogRecordManager] successOrFailedLogDicWith:logDic statusCode:response.statusCode errorInfo:result logTag:logTag];
            [[YWLogRecordTool shareLogRecordManager] saveLocalPatameterLog:failedDic];
            //上传错误参数
            if ([[WMHttpTool shareHttpTool] existenceNetwork]) {
                NSString *statusCode = [NSString stringWithFormat:@"statusCode: %@",@(response.statusCode).stringValue];
                [Bugly reportException:[NSException exceptionWithName:@"设备巡查接口错误" reason:statusCode userInfo:params]];
            }
            [records enumerateObjectsUsingBlock:^(YWInspectionEquipmentRecord* _Nonnull record, NSUInteger idx, BOOL* _Nonnull stop) {
                //更新上传状态
                [self updateInspectionEquipmentRecordUploadStatus:YWInspectionEquipmentRecordUploadStatusUnFinished inspectionEquipmentRecordId:record.equipmentRecordId];
            }];
            dispatch_group_leave(self.group);
        });
    }];
}

- (void)submitInspectionLocationRecords:(NSArray*)records{
    NSDictionary *headers = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headers;
    if (headers == nil) {dispatch_group_leave(self.group);return;}
    
    NSMutableDictionary* params = [NSMutableDictionary dictionary];
    __block YWBuilding *building = nil;
    [records enumerateObjectsUsingBlock:^(YWInspectionEquipmentRecord* _Nonnull record, NSUInteger idx, BOOL* _Nonnull stop) {
        building = [[YWBuildingManager shareManager] buildingWithLocationId:record.locationId];
        if (building == nil) {
            building = [[YWBuildingManager shareManager] buildingWithEquipmentId:record.equipment.equipmentId];
        }
        [params setValue:@(record.inspectionMissionId) forKey:[NSString stringWithFormat:@"records[%lu].inspectionMissionId", (unsigned long)idx]];
        [params setValue:@(record.inspectionLineId) forKey:[NSString stringWithFormat:@"records[%lu].inspectionLine.inspectionLineId", (unsigned long)idx]];
        
        [params setValue:building.buildingId?:@"" forKey:[NSString stringWithFormat:@"records[%lu].buildingId", (unsigned long)idx]];
        [params setValue:record.uniqueTag?:@"" forKey:[NSString stringWithFormat:@"records[%lu].uniqueTag", (unsigned long)idx]];
        [params setValue:record.detailUniqueTag?:[NSString stringWithFormat:@"%@_%ld",record.uniqueTag,(long)record.locationId] forKey:[NSString stringWithFormat:@"records[%lu].detailUniqueTag", (unsigned long)idx]];
        
        [params setValue:record.note?:@"" forKey:[NSString stringWithFormat:@"records[%lu].note", (unsigned long)idx]];
        [params setValue:@(record.status) forKey:[NSString stringWithFormat:@"records[%lu].resultCode", (unsigned long)idx]];
        [params setValue:@(record.locationId) forKey:[NSString stringWithFormat:@"records[%lu].location.locationId", (unsigned long)idx]];
        NSArray* recordPic = [[YWKeepWatchMissionManager shareManager] recordPictureWithRecordId:record.equipmentRecordId recordType:YWPictureRecordTypeInspectionMission];
        [recordPic enumerateObjectsUsingBlock:^(YWPatrolPicture* _Nonnull picture, NSUInteger index, BOOL* _Nonnull stop) {
            [params setValue:picture.bigUrl ?: @"" forKey:[NSString stringWithFormat:@"records[%lu].pictures[%lu].url", (unsigned long)idx,(unsigned long)index]];
            [params setValue:picture.smallUrl ?: @"" forKey:[NSString stringWithFormat:@"records[%lu].pictures[%lu].thumbnailUrl", (unsigned long)idx,(unsigned long)index]];
            [params setValue:picture.smallUrl ?: @"" forKey:[NSString stringWithFormat:@"records[%lu].pictures[%lu].previewUrl", (unsigned long)idx,(unsigned long)index]];
        }];
        //报障信息
        [record.posTroubleArray enumerateObjectsUsingBlock:^(YWReportTroubleModel*  _Nonnull reportTroubleModel, NSUInteger troubleIdx, BOOL * _Nonnull stop) {
            //报障信息
            [params setValue:reportTroubleModel.uniqueTag?:@"" forKey:[NSString stringWithFormat:@"records[%lu].troubles[%lu].uniqueTag",(unsigned long)idx,(unsigned long)troubleIdx]];
            YWEquipment* equipment = reportTroubleModel.equipment;
            if (equipment && equipment.equipmentTypeId > 0) {
                [params setValue:@(equipment.locationId) forKey:[NSString stringWithFormat:@"records[%lu].troubles[%lu].location.locationId",(unsigned long)idx,(unsigned long)troubleIdx]];
                [params setValue:@(equipment.equipmentTypeId) forKey:[NSString stringWithFormat:@"records[%lu].troubles[%lu].equipmentType.equipmentTypeId",(unsigned long)idx,(unsigned long)troubleIdx]];
                [params setValue:equipment.equipmentId ?: @"" forKey:[NSString stringWithFormat:@"records[%lu].troubles[%lu].equipment.equipmentId",(unsigned long)idx,(unsigned long)troubleIdx]];
            }else{
                NSInteger locationId = reportTroubleModel.location.locationId;
                if (locationId == 0 && records.count>0) {
                    YWInspectionEquipmentRecord *record = records[0];
                    locationId = record.locationId;
                }
                [params setValue:@(locationId) forKey:[NSString stringWithFormat:@"records[%lu].troubles[%lu].location.locationId",(unsigned long)idx,(unsigned long)troubleIdx]];
            }
            
            [params setValue:reportTroubleModel.qrcodeId ?: @"" forKey:[NSString stringWithFormat:@"records[%lu].troubles[%lu].qrcodeId",(unsigned long)idx,(unsigned long)troubleIdx]];
            [params setValue:reportTroubleModel.note?:@"" forKey:[NSString stringWithFormat:@"records[%lu].troubles[%lu].note",(unsigned long)idx,(unsigned long)troubleIdx]];
            YWBuilding* building = reportTroubleModel.building;
            
            if (building==nil && reportTroubleModel.equipment.equipmentId.length) {
                building = [[YWBuildingManager shareManager] buildingWithEquipmentId:reportTroubleModel.equipment.equipmentId];
            }
            if (building == nil && reportTroubleModel.location.locationId>0) {
                building = [[YWBuildingManager shareManager] buildingWithLocationId:reportTroubleModel.location.locationId];
            }
            [params setValue:building.buildingId ?: @"" forKey:[NSString stringWithFormat:@"records[%lu].troubles[%lu].building.buildingId",(unsigned long)idx,(unsigned long)troubleIdx]];
            NSArray *troublePicureArray = [[YWDBTool shareDBTool] picturesWithMissionId:reportTroubleModel.troubleId maintenanceType:reportTroubleModel.maintenanceTypeId];
            [troublePicureArray enumerateObjectsUsingBlock:^(YWPicture* _Nonnull picture, NSUInteger picIdx, BOOL* _Nonnull stop) {
                [params setValue:picture.bigPictureUrl ?: @"" forKey:[NSString stringWithFormat:@"records[%lu].troubles[%lu].pictures[%lu].url",(unsigned long)idx,(unsigned long)troubleIdx,(unsigned long)picIdx]];
                [params setValue:picture.smallPictureUrl ?: @"" forKey:[NSString stringWithFormat:@"records[%lu].troubles[%lu].pictures[%lu].thumbnailUrl",(unsigned long)idx,(unsigned long)troubleIdx,(unsigned long)picIdx]];
                [params setValue:picture.smallPictureUrl ?: @"" forKey:[NSString stringWithFormat:@"records[%lu].troubles[%lu].pictures[%lu].previewUrl",(unsigned long)idx,(unsigned long)troubleIdx,(unsigned long)picIdx]];
            }];
        }];
        
        long long executeTime = [YWCommonTool numberWithTime:record.executeTime];
        [params setValue:@(executeTime) forKey:[NSString stringWithFormat:@"records[%lu].clientExecuteTime", (unsigned long)idx]];
        long long nowTime = [YWCommonTool numberWithTime:[[NSDate date] timeIntervalSince1970]*1000];
        [params setValue:@(nowTime) forKey:[NSString stringWithFormat:@"records[%lu].clientCurrentTime", (unsigned long)idx]];
    }];
    NSString *url = [YWCommonTool submitInspectionLocationRecordUrl];
    YWLog(@"%@", params);
    //保存请求前的参数日志
    NSString *logTag = [YWCommonTool randStringId];
    NSMutableDictionary * logDic = [[YWLogRecordTool shareLogRecordManager] getLogDictionaryWithModule:@"位置巡查" interface:url params:params headers:headers tag:logTag];
    [[YWLogRecordTool shareLogRecordManager] saveLocalPatameterLog:logDic];
    
    [[WMHttpTool shareHttpTool] postWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            YWLog(@"提交设备巡查记录成功");
            [records enumerateObjectsUsingBlock:^(YWInspectionEquipmentRecord* _Nonnull record, NSUInteger idx, BOOL* _Nonnull stop) {
                [self updateInspectionEquipmentRecordUploadStatus:YWInspectionEquipmentRecordUploadStatusFinished inspectionEquipmentRecordId:record.equipmentRecordId];
            }];
            NSArray* reportTroubleArray = [YWReportTroubleModel mj_objectArrayWithKeyValuesArray:[json objectForKey:@"troubles"]];
            if (reportTroubleArray.count) {
                [reportTroubleArray enumerateObjectsUsingBlock:^(YWReportTroubleModel*  _Nonnull reportTrouble, NSUInteger idx, BOOL * _Nonnull stop) {
                    //保存流转信息
                    [[YWCirculationManager shareManager] updateCirculationInfoWithArray:reportTrouble.circulationInfos];
                    //更新关联表的troubleId
                    [[YWMissionManager shareManager] updateRecordAndPostTroubleRelTableUniqueTag:reportTrouble.uniqueTag newTroubleId:reportTrouble.troubleId];
                    //修改本地的troubleId
                    [[YWMissionManager shareManager] updatePostTroubleId:reportTrouble uniqueTag:reportTrouble.uniqueTag];
                }];
            }
            
            //保存请求成功的参数日志
            NSMutableDictionary * successDic =
            [[YWLogRecordTool shareLogRecordManager] successOrFailedLogDicWith:logDic statusCode:response.statusCode errorInfo:@"无" logTag:logTag];
            [[YWLogRecordTool shareLogRecordManager] saveLocalPatameterLog:successDic];
            dispatch_group_leave(self.group);
        });
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            YWLog(@"%s,error:%@", __func__, error.localizedDescription);
            //保存请求失败的参数日志
            NSString * result = [NSString stringWithFormat:@"%s,error:%@", __func__, error.localizedDescription];
            NSMutableDictionary * failedDic = [[YWLogRecordTool shareLogRecordManager] successOrFailedLogDicWith:logDic statusCode:response.statusCode errorInfo:result logTag:logTag];
            [[YWLogRecordTool shareLogRecordManager] saveLocalPatameterLog:failedDic];
            
            //上传错误参数
            if ([[WMHttpTool shareHttpTool] existenceNetwork]) {
                NSString *statusCode = [NSString stringWithFormat:@"statusCode: %@",@(response.statusCode).stringValue];
                [Bugly reportException:[NSException exceptionWithName:@"位置巡查接口错误" reason:statusCode userInfo:params]];
            }
            
            [records enumerateObjectsUsingBlock:^(YWInspectionEquipmentRecord* _Nonnull record, NSUInteger idx, BOOL* _Nonnull stop) {
                //更新上传状态
                [self updateInspectionEquipmentRecordUploadStatus:YWInspectionEquipmentRecordUploadStatusUnFinished inspectionEquipmentRecordId:record.equipmentRecordId];
            }];
            dispatch_group_leave(self.group);
        });
    }];
}

- (BOOL)updatePatrolPictureWithArray:(NSArray*)patrolPictures{
    return [[YWDBTool shareDBTool] updatePatrolPictureWithArray:patrolPictures];
}

- (BOOL)isExistRecordWithUniqueTag:(NSString *)uniqueTag equipmentId:(NSString*)equipmentId{
    return [[YWInspectionMissionDBManager shareManager] isExistRecordWithUniqueTag:uniqueTag equipmentId:equipmentId];
}
- (BOOL)isExistEquipmentWithLineId:(NSInteger)inspectionLineId{
    return [[YWInspectionMissionDBManager shareManager] isExistEquipmentWithLineId:inspectionLineId];
}
- (BOOL)isExistLocationWithLineId:(NSInteger)inspectionLineId{
    return [[YWInspectionMissionDBManager shareManager] isExistLocationWithLineId:inspectionLineId];
}

-(NSArray*)matchInspectionMissionsWithQrcodeID:(NSString*)qrcodeId orLocationId:(NSInteger)locationId{
//    NSInteger locationId = [[YWEquipmentManager shareManager]locationIdWithQrcodeId:qrcodeId];
    NSArray *missions = [self twoTypeInspectionMissions];
    NSMutableArray *missionArr = [NSMutableArray array];
    if (missions.count==2) {
        [missions[1] enumerateObjectsUsingBlock:^(YWInspectionMissionModel*  _Nonnull missionModel, NSUInteger idx, BOOL * _Nonnull stop) {
            YWInspectionMissionModel *mission = [self judgeTheInspectionMission:missionModel qrcodeId:qrcodeId orLocationId:locationId];
            if (mission && [YWCommonTool containSelfInHandlers:mission.executors]) {
                [missionArr addObject:mission];
            }
        }];
        [missions[0] enumerateObjectsUsingBlock:^(YWInspectionMissionModel*  _Nonnull missionModel, NSUInteger idx, BOOL * _Nonnull stop) {
            YWInspectionMissionModel *mission = [self judgeTheInspectionMission:missionModel qrcodeId:qrcodeId orLocationId:locationId];
            if (mission && [YWCommonTool containSelfInHandlers:mission.executors]) {
                [missionArr addObject:mission];
            }
        }];
    }
    return missionArr;
}
-(NSArray*)matchInspectionMissionsWithQrcodeID:(NSString*)qrcodeId orLocationId:(NSInteger)locationId inspectionLineType:(YWInspectionLineType)lineType equipmentId:(NSString *)equipmentId{
    NSArray *missions = [self twoTypeInspectionMissions];
    NSMutableArray *missionArr = [NSMutableArray array];
    if (missions.count==2) {
        if (lineType == YWInspectionLineTypeEquipment) {
            [missions[1] enumerateObjectsUsingBlock:^(YWInspectionMissionModel*  _Nonnull missionModel, NSUInteger idx, BOOL * _Nonnull stop) {
                YWInspectionMissionModel *mission = [self judgeTheInspectionMission:missionModel qrcodeId:qrcodeId orLocationId:locationId];
                BOOL matchEqu = YES;
                if (mission && equipmentId.length > 0) {
                    NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K == %@", @"equipmentId", equipmentId];
                    NSArray *array = [mission.inspectionLine.equipments filteredArrayUsingPredicate:searchPredicate];
                    matchEqu = array.count > 0 ? YES : NO;
                }
                if (mission && matchEqu && [YWCommonTool containSelfInHandlers:mission.executors]) {
                    [missionArr addObject:mission];
                }
            }];
        }else{
            [missions[0] enumerateObjectsUsingBlock:^(YWInspectionMissionModel*  _Nonnull missionModel, NSUInteger idx, BOOL * _Nonnull stop) {
                YWInspectionMissionModel *mission = [self judgeTheInspectionMission:missionModel qrcodeId:qrcodeId orLocationId:locationId];
                if (mission && [YWCommonTool containSelfInHandlers:mission.executors]) {
                    [missionArr addObject:mission];
                }
            }];
        }
    }
    return missionArr;
}

- (YWInspectionMissionModel*)judgeTheInspectionMission:(YWInspectionMissionModel*)inspectionMissionModel qrcodeId:(NSString*)qrcodeId orLocationId:(NSInteger)locationId{
    __block YWInspectionMissionModel *inspectionMission = inspectionMissionModel;
    
    YWInspectionJudgeType judgeType = [[YWInspectionMissionManager shareManager] judgeTypeWithMission:inspectionMission];
    if (judgeType != YWInspectionJudgeTypeMatch) {
        //        [YWCommonTool showTextHUDWithContent:[[YWInspectionMissionManager shareManager] typeNameWithJudgeType:judgeType]];
        return nil;
    }
    
    NSString *uniqueTag = [YWCommonTool uniqueTagWithMission:inspectionMission];
    __block YWInspectionLineRecord *looperRecord = [[YWInspectionMissionManager shareManager] latestInspectionLineRecordUniqueTag:uniqueTag];
    YWInspectionEquipmentQrcodeResult pointJudge = 0;
    NSArray *pointRecord = [[YWInspectionMissionManager shareManager]inspectionEquipmentRecordWithUniqueTag:looperRecord.uniqueTag];
    if (inspectionMission.inspectionLine.lineType==YWInspectionLineTypeEquipment) {
        NSArray *equipmentArray = [[YWInspectionMissionManager shareManager] allInspectionEquipmentWithLineId:inspectionMission.inspectionLine.inspectionLineId];
        
        NSArray *allNeedInspectionEquipment = [[YWInspectionMissionManager shareManager] allInspectionEquipmentWithLineId:inspectionMission.inspectionLine.inspectionLineId qrcodeId:qrcodeId orLocationId:locationId];
        pointJudge = [[YWInspectionMissionManager shareManager]judgeInspectionWithInspectionEquipment:equipmentArray equipmentRecord:pointRecord qrcodeEquipment:allNeedInspectionEquipment];
    }else{
        NSArray *allLocations = [[YWInspectionMissionManager shareManager] allInspectionLocationWithInspectionLineId:inspectionMission.inspectionLine.inspectionLineId];
        
        NSInteger lllllocationId = qrcodeId ? [[YWEquipmentManager shareManager]locationIdWithQrcodeId:qrcodeId] : locationId;
        pointJudge = [[YWInspectionMissionManager shareManager]judgeInspectionPointWithLocation:allLocations pointRecord:pointRecord locationId:lllllocationId];
    }
    
    if (pointJudge==YWInspectionEquipmentQrcodeResultUnMatch) {
        return nil;
    }else if (pointJudge==YWInspectionEquipmentQrcodeResultHasPatrol){
        return nil;
    }else{
        if (looperRecord) {
            if (looperRecord.result >= YWInspectionLineRecordResultFinishAndTrouble) {
                return nil;
            }else{
                return inspectionMission;
            }
        }else{
            return inspectionMission;
        }
    }
}

- (NSArray *)needRequestInspectionlLines{
    return [[YWInspectionMissionDBManager shareManager] needRequestInspectionlLines];
}


- (void)requestInspectionMissionInfo:(NSInteger)inspectionMissionId complete:(void (^)(BOOL))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);};return;}
    
    NSString *url = [YWCommonTool getInspectionRecordAndReplyUrl];
    NSDictionary *params = @{@"inspectionMissionId":@(inspectionMissionId)};
    [[WMHttpTool shareHttpTool] getWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            YWInspectionMissionInfoJson *inspectionMissionMissionInfoJson = [YWInspectionMissionInfoJson mj_objectWithKeyValues:json];
            if (inspectionMissionMissionInfoJson) {
                //更新任务的最新一条记录
                [[YWInspectionMissionDBManager shareManager] updateInspectionLineRecordWithNewWorkData:inspectionMissionMissionInfoJson.latestRecord?@[inspectionMissionMissionInfoJson.latestRecord]:nil];
                
                __block NSMutableArray *totalEquipmentRecordArray = [NSMutableArray array];
                __block NSMutableArray *picturesArray = [NSMutableArray array];
                __block YWInspectionEquipmentRecord *equRecord = nil;
                
                [inspectionMissionMissionInfoJson.latestRecord.allKindRecord enumerateObjectsUsingBlock:^(YWInspectionEquipmentRecord*  _Nonnull detailPointRecord, NSUInteger idx, BOOL * _Nonnull stop) {
                    equRecord = [[YWInspectionEquipmentRecord alloc]init];
                    equRecord.inspectionLineId = inspectionMissionMissionInfoJson.latestRecord.inspectionLineId;
                    equRecord.inspectionMissionId = inspectionMissionId;
                    equRecord.uniqueTag = inspectionMissionMissionInfoJson.latestRecord.uniqueTag;
                    equRecord.detailUniqueTag = detailPointRecord.detailUniqueTag;
                    equRecord.executeTime = detailPointRecord.executeTime;
                    equRecord.executor = detailPointRecord.executor;
                    equRecord.note = detailPointRecord.note;
                    equRecord.equipment = detailPointRecord.equipment;
                    
                    equRecord.recordType = (inspectionMissionMissionInfoJson.latestRecord.recordType == YWInspectionLineTypeEquipment)?YWInspectionEquipmentRecordTypeEquipment:YWInspectionEquipmentRecordTypeLocation;
                    
                    equRecord.locationId = detailPointRecord.locationId;
                    if (equRecord.recordType == YWInspectionEquipmentRecordTypeEquipment && equRecord.equipment) {
                        equRecord.equipmentRecordId = [NSString stringWithFormat:@"%@_%@", equRecord.uniqueTag,equRecord.equipment.equipmentId];
                    }else{
                        equRecord.equipmentRecordId = [NSString stringWithFormat:@"%@_%ld", equRecord.uniqueTag,(long)equRecord.locationId];
                    }
                    
                    equRecord.equipmentFields = detailPointRecord.equipmentFields;
                    equRecord.status = detailPointRecord.status;
                    equRecord.uploadStatus = YWPatrolPointRecordUploadStatusFinished;
                    [detailPointRecord.pictures enumerateObjectsUsingBlock:^(YWPatrolPicture*  _Nonnull patrolPicture, NSUInteger idx, BOOL * _Nonnull stop) {
                        patrolPicture.recordId = equRecord.equipmentRecordId;
                        patrolPicture.pictureId = [YWCommonTool randStringId];
                        patrolPicture.pictureName = @"";
                        patrolPicture.isLocalImage = NO;
                        patrolPicture.uploadStatus = YWPictureRecordUploadStatusSuccess;
                        patrolPicture.recordType = YWPictureRecordTypeInspectionMission;
                        [picturesArray addObject:patrolPicture];
                    }];
                    
                    [totalEquipmentRecordArray addObject:equRecord];
                    //是否建立与报障的关联
                    [detailPointRecord.posTroubleArray enumerateObjectsUsingBlock:^(YWTroubleIdJson*  _Nonnull troubleIdJson, NSUInteger idx, BOOL * _Nonnull stop) {
                        if (![[YWMissionManager shareManager] isExistRelWithTroubleId:troubleIdJson.troubleId detailUniqueTag:equRecord.detailUniqueTag]) {
                            [[YWMissionManager shareManager] saveRecordAndPostTroubleRelWithtroubleId:troubleIdJson.troubleId detailUniqueTag:equRecord.detailUniqueTag];
                        }
                    }];
                    
                }];
                [[YWInspectionMissionManager shareManager] updateInspectionEquipmentRecordWithArray:totalEquipmentRecordArray];
                [[YWKeepWatchMissionManager shareManager] updatePatrolPictureWithNewWorkData:picturesArray];
                
                if (totalEquipmentRecordArray.count) {
                    NSMutableArray *fieldRecorsArray = [NSMutableArray array];
                    [totalEquipmentRecordArray enumerateObjectsUsingBlock:^(YWInspectionEquipmentRecord*  _Nonnull equRecord, NSUInteger idx, BOOL * _Nonnull stop) {
                        [equRecord.equipmentFields enumerateObjectsUsingBlock:^(YWEquipmentFieldRecord*  _Nonnull fieldRecord, NSUInteger idx, BOOL * _Nonnull stop) {
                            fieldRecord.uniqueTag = equRecord.equipmentRecordId;
                            fieldRecord.maintenanceTypeId = YWMaintenanceTypePatrol;
                            [fieldRecorsArray addObject:fieldRecord];
                        }];
                    }];
                    [[YWMissionManager shareManager] updateEquipmentFieldRecords:fieldRecorsArray];
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                if (complete) {
                    complete(YES);
                }
            });
        });
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(NO);
            if ([[WMHttpTool shareHttpTool] existenceNetwork]) {
                [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"requestFailed", nil)];
            }
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (void)requestInspectionLineWithLineArray:(NSArray *)inspectionLineArray complete:(void (^)(BOOL))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);};return;}
    
    NSString* url = [YWCommonTool getInspectionLineDetailUrl];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [inspectionLineArray enumerateObjectsUsingBlock:^(YWInspectionLineModel*  _Nonnull inspectionLine, NSUInteger idx, BOOL * _Nonnull stop) {
        [params setValue:@(inspectionLine.inspectionLineId) forKey:[NSString stringWithFormat:@"inspectionLines[%lu].inspectionLineId",(unsigned long)idx]];
        if (inspectionLine.updateTime) {
            [params setValue:@(inspectionLine.updateTime) forKey:[NSString stringWithFormat:@"inspectionLines[%lu].updateTime",(unsigned long)idx]];
        }
    }];
    YWLog(@"url---%@,%@",url,params);
    [[WMHttpTool shareHttpTool] getWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSArray* inspectionLineArray = [YWInspectionLineModel mj_objectArrayWithKeyValuesArray:json];
            //保存线路
            if (inspectionLineArray.count) {
                [[YWInspectionMissionDBManager shareManager] updateInspectionLineWithArray:inspectionLineArray];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                if (complete) {
                    complete(YES);
                }
            });
        });
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(NO);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (void)requestInspectionEquipmentRecordWithEquipmentIds:(NSString *)equipmentIds page:(NSInteger)page pageSize:(NSInteger)pageSize completeBlock:(void (^)(NSInteger))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(0);}return;}
    NSMutableDictionary* params = [NSMutableDictionary dictionary];
    [params setObject:equipmentIds forKey:@"equipmentIds"];
    if (page) {
        [params setObject:@(page) forKey:@"page"];
    }
    if (pageSize) {
        [params setObject:@(pageSize) forKey:@"pageSize"];
    }
    [[WMHttpTool shareHttpTool] getWithUrl:[YWCommonTool getEquipmentInspectionRecordUrl] params:params success:^(NSHTTPURLResponse* response, id json) {
        NSArray* inspectionRecordsArray = [YWInspectionEquipmentRecord mj_objectArrayWithKeyValuesArray:json];
        NSMutableArray *picturesArray = [NSMutableArray array];
        
        [inspectionRecordsArray enumerateObjectsUsingBlock:^(YWInspectionEquipmentRecord*  _Nonnull equRecord, NSUInteger idx, BOOL * _Nonnull stop) {
            if (equRecord.equipment.equipmentId.length>0) {
                equRecord.equipmentRecordId = [NSString stringWithFormat:@"%@_%@", equRecord.uniqueTag,equRecord.equipment.equipmentId];
            }else{
                equRecord.equipmentRecordId = [NSString stringWithFormat:@"%@_%ld", equRecord.uniqueTag,(long)equRecord.locationId];
            }
            //这里都是设备的巡查，没有位置的巡查
            equRecord.recordType = YWInspectionEquipmentRecordTypeEquipment;
            
            equRecord.uploadStatus = YWPatrolPointRecordUploadStatusFinished;
            [equRecord.pictures enumerateObjectsUsingBlock:^(YWPatrolPicture*  _Nonnull patrolPicture, NSUInteger idx, BOOL * _Nonnull stop) {
                patrolPicture.recordId = equRecord.equipmentRecordId;
                patrolPicture.pictureId = [YWCommonTool randStringId];
                patrolPicture.pictureName = @"";
                patrolPicture.isLocalImage = NO;
                patrolPicture.uploadStatus = YWPictureRecordUploadStatusSuccess;
                patrolPicture.recordType = YWPictureRecordTypeInspectionMission;
                [picturesArray addObject:patrolPicture];
            }];
            //是否建立与报障的关联
            [equRecord.posTroubleArray enumerateObjectsUsingBlock:^(YWTroubleIdJson*  _Nonnull troubleIdJson, NSUInteger idx, BOOL * _Nonnull stop) {
                if (![[YWMissionManager shareManager] isExistRelWithTroubleId:troubleIdJson.troubleId detailUniqueTag:equRecord.detailUniqueTag]) {
                    [[YWMissionManager shareManager] saveRecordAndPostTroubleRelWithtroubleId:troubleIdJson.troubleId detailUniqueTag:equRecord.detailUniqueTag];
                }
            }];
        }];
        [[YWInspectionMissionManager shareManager] updateInspectionEquipmentRecordWithArray:inspectionRecordsArray];
        [[YWKeepWatchMissionManager shareManager] updatePatrolPictureWithNewWorkData:picturesArray];
        if (inspectionRecordsArray.count) {
            NSMutableArray *fieldRecorsArray = [NSMutableArray array];
            [inspectionRecordsArray enumerateObjectsUsingBlock:^(YWInspectionEquipmentRecord*  _Nonnull equRecord, NSUInteger idx, BOOL * _Nonnull stop) {
                [equRecord.equipmentFields enumerateObjectsUsingBlock:^(YWEquipmentFieldRecord*  _Nonnull fieldRecord, NSUInteger idx, BOOL * _Nonnull stop) {
                    fieldRecord.uniqueTag = equRecord.equipmentRecordId;
                    fieldRecord.maintenanceTypeId = YWMaintenanceTypePatrol;
                    [fieldRecorsArray addObject:fieldRecord];
                }];
            }];
            [[YWMissionManager shareManager] updateEquipmentFieldRecords:fieldRecorsArray];
        }
        
        if (complete) {
            complete(inspectionRecordsArray.count);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(0);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

@end
